This repository has been archived by the owner on Oct 28, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
telegram_bot.py
executable file
Β·431 lines (358 loc) Β· 13.7 KB
/
telegram_bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A telegram bot to track activites of the
participants of @BEARly's #100DaysOfCode Challenge.
"""
from datetime import date, timedelta
from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, ParseMode
from telegram import InlineQueryResultArticle, InputTextMessageContent
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram.ext import InlineQueryHandler
from GitActivity import *
import os
import logging
import dataset
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
db = dataset.connect(os.environ['DATABASE_URL'])
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
HELP_TEXT = """/gitname `github username` to set your username
/todo `topicname` to add a new task
/done `topicname` to add a finished task
/reminder `on|off` to turn on or turn off reminder
@bearlyhdocbot <space> to mark tasks as finished
*Private commands*
/leaderboard to display leaderboard
/help to display this help
/tasks to list your tasks and delete them.
/streak to see number of days you've been active.
"""
users = db['users']
tasks = db['tasks']
github_activity = db['github_activity']
def addToDo(user, task):
tasks.insert(dict(user_id=user.id, text=task, finished=False,
daystarted=date.today().isoformat()))
def addDone(user, task):
tasks.insert(dict(
user_id=user.id,
text=task,
finished=True,
daystarted=date.today().isoformat(),
dayfinished=date.today().isoformat()
))
def getTasks(user):
its = []
for task in tasks:
if(task['user_id'] == user.id):
its += [task['text']]
print(task['text'])
return its
def start(bot, update):
"""Send a message when the command /start is issued."""
user = update.message.from_user
reply = '_Dear {}_,\n\n' + \
'*Welcome to @BEARlyDev\'s #100DaysOfCodeChallenge*,\n\n' + \
'Start by setting your github username ' + \
'using /gitname <space> _username_.'
reply = reply.format(user.first_name)
update.message.reply_text(
reply,
parse_mode='MarkDown',
reply_markup=ReplyKeyboardRemove()
)
def gitname(bot, update):
user = update.message.from_user
git_name = update.message.text.replace('/gitname', '')
git_name = git_name.replace(' ', '')
if(len(git_name) < 3):
update.message.reply_text('π Invalid github username, try again.')
else:
print('git name: {}'.format(git_name))
if(users.count(user_id=user.id) > 0):
users.update(dict(user_id=user.id, username=user.username,
gitname=git_name), ['user_id'])
else:
users.insert(dict(
user_id=user.id,
username=user.username,
gitname=git_name,
score=0
))
update.message.reply_text(
'π Git username successfully set,\n' +
'use /help to continue. Don\'t forget to join our group @BEARlyDev'
)
def help(bot, update):
# no need of reply for commands from group chats
if update.message.chat_id < 0:
return
"""Send a message when the command /help is issued."""
# update.message.reply_text(HELP_TEXT, parse_mode = 'MarkDown',
# reply_markup=ReplyKeyboardRemove())
update.message.reply_text(HELP_TEXT, parse_mode='MarkDown')
def alarm(bot, job):
"""Send the alarm message."""
usrname = str(bot.getChat(job.context).username)
d = dataset.connect('sqlite:///todo.db')
t = d['tasks']
task = list(t.find(user_id=job.context, finished=False))
task_count = len(task)
REMINDER_TEXT = "Hi @{0},\nYou have {1} pending tasks.\n".format(
usrname,
task_count
)
for t in task:
line = "β’ {0}\n".format(dict(t)['text'])
REMINDER_TEXT += line
bot.send_message(job.context, text=REMINDER_TEXT)
def todo(bot, update):
# def todo(bot, update, args, job_queue, chat_data):
"""Send a message when the command /help is issued."""
if update.message.chat.type != 'group':
update.message.reply_text(
'π‘ This command is a group only command!. ' +
'Let others know what you are working on π'
)
return
task = update.message.text[6:]
print('task : ' + task)
user = update.message.from_user
if(task == ''):
update.message.reply_text('π‘ The format is /todo <space> Taskname ')
else:
addToDo(user, task)
update.message.reply_text(
'π£β @{} added task : {}.\n ({} pending tasks)'.format(
user.username,
task,
str(tasks.count(user_id=user.id, finished=False))
)
)
def reminder(bot, update, args, job_queue, chat_data):
cmd = str(update.message.text[10:])
print(job_queue.jobs())
print(cmd)
if cmd == 'on':
update.message.reply_text('Reminder turned on\n')
for j in job_queue.jobs():
j.schedule_removal()
job_queue.stop()
job = job_queue.run_repeating(alarm, interval=86400, first=0,
context=update.message.chat_id)
job_queue.start()
job.enabled = True
elif cmd == 'off':
for j in job_queue.jobs():
j.schedule_removal()
update.message.reply_text('Reminder turned off\n')
job_queue.stop()
else:
update.message.reply_text(
'Handle reminders with /reminder on or /reminder off\n')
def done(bot, update):
"""Send a message when the command /help is issued."""
if update.message.chat.type != 'group':
update.message.reply_text(
'π‘ This command is a group only command!. ' +
'Let others know what you are working on π'
)
return
task = update.message.text[6:]
print('done task : ' + task)
if(task == ''):
update.message.reply_text('π‘ The format is /done <space> _Taskname_')
else:
user = update.message.from_user
addDone(user, task)
cur_score = users.find_one(user_id=user.id)['score']
cur_score += 10
users.update(dict(user_id=user.id, score=cur_score), ['user_id'])
update.message.reply_text(
'π @{} finished task : {}.\n ({} pending tasks)'.format(
user.username, task, str(
tasks.count(
user_id=user.id, finished=False))))
def leaderboard(bot, update):
"""Send a message when the command /help is issued."""
delta = timedelta(days=1)
enddate = date.today()
# disable for group chat
if update.message.chat_id < 0:
return
uss = []
my_score = 0
for user in users:
total_score = user['score'] # + streak_score
statement = 'SELECT count(dayfinished) as count FROM ' + \
'(SELECT DISTINCT dayfinished FROM tasks WHERE user_id={});' \
.format(
user['user_id']
)
streak = db.query(statement)
for row in streak:
streak_score = row['count']
break
# streak_score = int((streak_score*(streak_score + 1))/2)
git_score = GitActivity().get_total_commit_count(user['gitname'])
uss.append([user['gitname'], total_score, streak_score, git_score])
if user['user_id'] == update.message.from_user.id:
my_score = total_score
uss.sort(key=lambda x: (-x[1], -x[2]))
lb = " π Leaderboard \n\n"
i = 0
for u in uss:
i += 1
lb += ('{}. {} - {} π₯{} πΎ{} \n').format(i, u[0], u[1], u[2], u[3])
lb += "\n\n Your score : {}".format(str(my_score))
update.message.reply_text(lb)
def tasks_(bot, update):
reply = 'Your tasks are\n\n'
user = update.message.from_user
# if the command is from a group chat no need of reply
if update.message.chat_id < 0:
return
tasks2 = tasks.find(user_id=user.id)
for task in tasks2:
reply += 'β’ {}'.format(task['text'])
if task['finished']:
reply += ' - β
\n'
else:
reply += ' - β /delete_{}\n'.format(str(task['id']))
update.message.reply_text(reply)
def echo(bot, update):
"""Echo the user message."""
user = update.message.from_user
# disable for group chat
if update.message.chat_id < 0:
return
# print(update.message.text[:10])
update.message.reply_text(
'π Sorry, didnt get you, /help for list of commands')
def inlinequery(bot, update):
"""Handle the inline query."""
query = update.inline_query.query.lower()
user = update.inline_query.from_user
tasks2 = tasks.find(finished=False)
results = []
# print(query)
for task in tasks2:
if task['user_id'] == user.id and task['finished'] is False:
results.append(InlineQueryResultArticle(
id=str(task['id']),
title=task['text'],
description='β³ Ongoing',
# description='β
Finished' if task['finished'] else 'β³ Ongoing'
input_message_content=InputTextMessageContent(
'/completed {}'.format(task['id'])))
)
update.inline_query.answer(results, cache_time=0, is_personal=True)
def streak(bot, update):
# if the command is from a group chat no need of reply
if update.message.chat_id < 0:
return
user = update.message.from_user
statement = 'SELECT count(dayfinished) as count FROM ' + \
'(SELECT DISTINCT dayfinished FROM tasks WHERE user_id={});'.format(
user.id
)
streak = db.query(statement)
for row in streak:
streak_score = row['count']
break
update.message.reply_text(
'π₯ Your streak : {} days'.format(streak_score),
parse_mode='MarkDown')
def completed(bot, update):
if update.message.chat_id != -1001187606231:
update.message.reply_text(
'π‘ You can only mark tasks as completed from the group itself, ' +
'update your progress with community! πΉ')
return
user = update.message.from_user
try:
task_id = update.message.text.replace('/completed', '').strip()
if(tasks.count(user_id=user.id, id=task_id, finished=False) > 0):
tasks.update(dict(
user_id=user.id,
id=task_id,
finished=True,
dayfinished=date.today().isoformat()
), ['id', 'user_id'])
cur_score = users.find_one(user_id=user.id)['score']
cur_score += 10
users.update(dict(user_id=user.id, score=cur_score), ['user_id'])
reply = 'π @{} completed task : {}.\n ({} pending tasks)'.format(
user.username, tasks.find_one(
id=task_id)['text'], str(
tasks.count(
user_id=user.id, finished=False)))
update.message.reply_text(reply, parse_mode='MarkDown')
else:
update.message.reply_text(
'π‘ Unknown error occurred report @ir5had',
parse_mode='MarkDown')
except Exception as e:
print(e)
update.message.reply_text(
'πΎ Unknown error occurred report the error @ir5had',
parse_mode='MarkDown')
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
def command_handler(bot, update):
# disable for group chat
if update.message.chat_id < 0:
return
if update.message.text[:7] == '/delete':
try:
task_id = int(update.message.text.split('_')[1])
tasks.delete(id=task_id)
reply = 'Task deleted.'
update.message.reply_text(reply)
except BaseException:
update.message.reply_text(
'Deletion error occurred',
parse_mode='MarkDown')
def main():
"""Start the bot."""
# Create the EventHandler and pass it your bot's token.
updater = Updater(os.environ['TG_BOT_TOKEN'])
j = updater.job_queue
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("gitname", gitname))
dp.add_handler(CommandHandler("help", help))
# dp.add_handler(CommandHandler("todo", todo))
dp.add_handler(CommandHandler("done", done))
dp.add_handler(CommandHandler("completed", completed))
dp.add_handler(CommandHandler("tasks", tasks_))
dp.add_handler(CommandHandler("leaderboard", leaderboard))
dp.add_handler(CommandHandler("streak", streak))
dp.add_handler(InlineQueryHandler(inlinequery))
dp.add_handler(CommandHandler("todo", todo))
dp.add_handler(CommandHandler("reminder", reminder,
pass_args=True,
pass_job_queue=True,
pass_chat_data=True))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, echo))
dp.add_handler(MessageHandler(Filters.command, command_handler))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()