forked from danigm/gitlab-telegram-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
87 lines (71 loc) · 2.21 KB
/
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
#!/usr/bin/env python
import time
import requests
from threading import Thread
class Bot:
def __init__(self):
try:
self.token = open('token').read().split()[0]
except:
raise Exception("The token file is invalid")
self.api = 'https://api.telegram.org/bot%s/' % self.token
try:
self.offset = int(open('offset').read().split()[0])
except:
self.offset = 0
self.me = self.botq('getMe')
self.running = False
def botq(self, method, params=None):
url = self.api + method
params = params if params else {}
return requests.post(url, params).json()
def msg_recv(self, msg):
''' method to override '''
pass
def text_recv(self, txt, chatid):
''' method to override '''
pass
def updates(self):
data = {'offset': self.offset}
r = self.botq('getUpdates', data)
for up in r['result']:
if 'message' in up:
self.msg_recv(up['message'])
elif 'edited_message' in up:
self.msg_recv(up['edited_message'])
else:
# not a valid message
break
try:
txt = up['message']['text']
self.text_recv(txt, self.get_to_from_msg(up['message']))
except:
pass
self.offset = up['update_id']
self.offset += 1
open('offset', 'w').write('%s' % self.offset)
def get_to_from_msg(self, msg):
to = ''
try:
to = msg['chat']['id']
except:
to = ''
return to
def reply(self, to, msg):
if type(to) not in [int, str]:
to = self.get_to_from_msg(to)
resp = self.botq('sendMessage', {'chat_id': to, 'text': msg, 'disable_web_page_preview': True, 'parse_mode': 'Markdown'})
return resp
def run(self):
self.running = True
while self.running:
self.updates()
time.sleep(1)
def run_threaded(self):
t = Thread(target=self.run)
t.start()
def stop(self):
self.running = False
if __name__ == '__main__':
bot = Bot()
bot.run()