-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
91 lines (67 loc) · 2.74 KB
/
app.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
import logging
import time
from flask import Flask, request
from telegram import Bot, Update, ReplyKeyboardMarkup
from telegram.ext import CommandHandler, MessageHandler, Filters, Dispatcher
from utils import get_reply, fetch_news, topics_keyboard
# enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
# telegram bot token
TOKEN = "1278923813:AAFbtdw_3IF1qLph2Os8n3Z2kHgStf8YlPs"
app = Flask(__name__)
@app.route('/')
def index():
return "Hello!"
@app.route(f'/{TOKEN}', methods=['GET', 'POST'])
def webhook():
"""webhook view which receives updates from telegram"""
# create update object from json-format request data
update = Update.de_json(request.get_json(), bot)
# process update
dp.process_update(update)
return "ok"
def start(bot, update):
"""callback function for /start handler"""
author = update.message.from_user.first_name
reply = "Hi! {}".format(author)
bot.send_message(chat_id=update.message.chat_id, text=reply)
def _help(bot, update):
"""callback function for /help handler"""
help_txt = "Hey! This is a help text."
bot.send_message(chat_id=update.message.chat_id, text=help_txt)
def news(bot, update):
"""callback function for /news handler"""
bot.send_message(chat_id=update.message.chat_id, text="Choose a category",
reply_markup=ReplyKeyboardMarkup(keyboard=topics_keyboard, one_time_keyboard=True))
def reply_text(bot, update):
"""callback function for text message handler"""
intent, reply = get_reply(update.message.text, update.message.chat_id)
if intent == "get_news":
articles = fetch_news(reply)
for article in articles:
bot.send_message(chat_id=update.message.chat_id, text=article['link'])
else:
bot.send_message(chat_id=update.message.chat_id, text=reply)
def echo_sticker(bot, update):
"""callback function for sticker message handler"""
bot.send_sticker(chat_id=update.message.chat_id,
sticker=update.message.sticker.file_id)
def error(bot, update):
"""callback function for error handler"""
logger.error("Update '%s' caused error '%s'", update, update.error)
bot = Bot(TOKEN)
try:
bot.set_webhook("https://frozen-thicket-87150.herokuapp.com//" + TOKEN)
time.sleep(5)
except Exception as e:
print(e)
dp = Dispatcher(bot, None)
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", _help))
dp.add_handler(CommandHandler("news", news))
dp.add_handler(MessageHandler(Filters.text, reply_text))
dp.add_handler(MessageHandler(Filters.sticker, echo_sticker))
dp.add_error_handler(error)
if __name__ == "__main__":
app.run(port=8443)