0%

考研倒计时telegram bot

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

开始使用优秀的python framework telepot编写机器人

虽然作者已经表明了I am no longer maintaining this library. Thanks for considering telepot.,但是这个库还是值得使用的。

第一步,申请机器人

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

第二步,搭建本地环境

本地python3环境,安装telepot使用pip install telepot

第三步,编写程序并调试

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

代码如下,需要更改cookiebot的名字,当然,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
import time
import telepot
import datetime
from telepot.loop import MessageLoop
import requests
import json

def getDiff():
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
return [year, diff]

def getToday():
url = 'http://open.iciba.com/dsapi/'
try:
r = requests.get(url)
today = json.loads(r.text)
return [today['content'], today['note'], today['tts']]
except:
return ['', '', '']

def handle(msg):
content_type, chat_type, chat_id = telepot.glance(msg)
global cnt
if content_type == 'text':
if msg['text'] == '/time' or msg['text'] == '/time@kaoyan_bot':
cnt += 1
print(cnt)
diff = getDiff()
text = '⚠️距离' + str(diff[0]) + '考研还有*' + str(diff[1]) + ' *天.'
today = getToday()
text = text + '\n\n📚每日一句: ' + today[0] + ' \n' + today[1]
text = text + '\n\n☁️' + '[学术加速器](https://v2.pyai.top)'
text = text + ' ⚡️' + '查询次数: ' + str(cnt)
# bot.sendMessage(chat_id, text=text , parse_mode= 'Markdown')
bot.sendAudio(chat_id, today[2], caption=text, parse_mode='Markdown')

TOKEN = 'xxxxxx:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'

cnt = 0
bot = telepot.Bot(TOKEN)
MessageLoop(bot, handle).run_as_thread()
print ('Listening ...')

# Keep the program running.
while 1:
time.sleep(10)

最终效果

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

如果对您有帮助,请我喝杯奶茶?