-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
70 lines (52 loc) · 2.09 KB
/
main.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
import emoji
import telepot
from flask import Flask, render_template, request
from flask_ini import FlaskIni
from telepot.delegate import create_open, pave_event_space, per_chat_id
from telepot.loop import MessageLoop
from db import create_comment, get_comments
app = Flask(__name__)
with app.app_context():
app.iniconfig = FlaskIni()
app.iniconfig.read('config.ini')
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
global comments
comment_title = request.form['title']
comment_content = request.form['content']
create_comment(comment_title, comment_content)
comments = get_comments()
return render_template('index.html', comments=comments)
class MessageCounter(telepot.helper.ChatHandler):
def __init__(self, *args, **kwargs):
super(MessageCounter, self).__init__(*args, **kwargs)
def on_chat_message(self, msg):
if not 'text' in msg or not msg['text'].startswith('/newcomment'):
self.sender.sendMessage(emoji.emojize("Sorry, but I can't understand you! :confused:", use_aliases=True))
return
text = msg['text'].lstrip()
_, comment = text.split(' ', 1) # Discard command
title, *content = comment.split('\n', 1) # Split comment members
if not content:
content = title
title = msg['from']['first_name']
if 'last_name' in msg['from']:
title += " "+msg['from']['last_name']
title += " says"
else:
content = content[0]
create_comment(title, content)
self.sender.sendMessage(emoji.emojize("Comment added to guestbook. :grin:", use_aliases=True))
bot = telepot.DelegatorBot(app.iniconfig.get('telegram', 'token'), [
pave_event_space()(
per_chat_id(), create_open, MessageCounter, timeout=10
),
])
# Discard Telegram updates when bot was offline
updates = bot.getUpdates()
if updates:
last_update_id = updates[-1]['update_id']
bot.getUpdates(offset=last_update_id + 1)
# Run telepot bot
MessageLoop(bot).run_as_thread()