0%

考研倒计时telegram bot

telegram是我用过的最好用的及时通讯软件,并且可玩性很高,官方提供了大量api接口供开发者使用。而且telegram没有任何广告,我第一次发现telegram是在codeforce的Footer处,telegramcodeforce的sponsor。

开始使用优秀的python framework python-telegram-bot编写机器人

第一步,申请机器人

直接在telegram搜索框中@BotFather,然后输入命令/newbot申请机器人,记住分配的token

第二步,搭建本地环境

本地python3环境,安装python-telegram-bot使用pip install python-telegram-bot --upgrade

第三步,编写程序并调试

当然这一步需要程序运行环境能够连接上telegram的服务器,我是在香港服务器上运行的。

代码如下,需要将token更改为你申请的bot的,当然,botcommand自定义即可。

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
import logging
import datetime
import time
import json
import requests
import _thread
import urllib3
from telegram.ext import Updater, CommandHandler, MessageHandler

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)

logger = logging.getLogger(__name__)
cnt = 0

def start(update, context):
global cnt; cnt += 1; print(cnt)
text = 'Hi! 欢迎使用考研倒计时查询🤖️。\n使用 /help 查询🤖️指令列表'
msg = update.message.reply_text(text)
try:
_thread.start_new_thread(delete_message_thread, (update, context, msg, text))
except:
print ("Error: unable to start thread.")


def help_command(update, context):
global cnt; cnt += 1; print(cnt)
text = '🏠指令列表:\n/start 开始使用\n/help 查询🤖️指令列表\n/time 查询考研倒计时'
msg = update.message.reply_text(text)
try:
_thread.start_new_thread(delete_message_thread, (update, context, msg, text))
except:
print ("Error: unable to start thread.")

def delete_message_thread(update, context, msg, text):
cnt = 30
while(cnt > 0):
time.sleep(6)
try:
msg.edit_text(text= text + '\n⏰此消息将在'+str(cnt-6)+'秒后销毁.', parse_mode='Markdown')
cnt -= 6
except Exception as e:
print("Message {} got exception {}".format(msg, e))
time.sleep(2)
context.bot.deleteMessage(chat_id=msg.chat.id, message_id=msg.message_id)

def getDiff(update, context):
global cnt; cnt += 1; print(cnt)
today = datetime.datetime.today()
kaoyan_day = datetime.datetime(today.year, 12, 19)
diff = (kaoyan_day - today).days
year = today.year + 1
if diff < 0:
next_kaoyan_day = datetime.datetime(today.year + 1, 12, 19)
diff = (next_kaoyan_day - today).days
year += 1
text = '⚠️距离' + str(year) + '考研还有*' + str(diff) + ' *天.'
msg = update.message.reply_text(text, parse_mode='Markdown')

def main():
updater = Updater(token='****************************************', use_context=True, request_kwargs={'read_timeout': 30, 'connect_timeout': 30})
# 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("help", help_command))
dp.add_handler(CommandHandler("time", getDiff))

updater.start_polling()
updater.idle()


if __name__ == '__main__':
main()

我的机器人链接: https://t.me/kaoyan_bot