Skip to content

Commit dac6527

Browse files
committed
wip
1 parent ab42c7f commit dac6527

3 files changed

Lines changed: 82 additions & 86 deletions

File tree

bot_logic.py

Lines changed: 71 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,12 @@
1010
# Non STL imports
1111
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ChatAction, ParseMode, Update
1212
from telegram.ext import (
13-
Updater, Filters, MessageHandler, CallbackQueryHandler, CallbackContext, CommandHandler)
13+
ContextTypes,
14+
CallbackQueryHandler,
15+
CommandHandler,
16+
MessageHandler,
17+
filters,
18+
)
1419
from typing import Dict, Final
1520

1621
# Local imports
@@ -33,13 +38,13 @@
3338
bsasTz = pytz.timezone("America/Argentina/Buenos_Aires")
3439

3540

36-
def start(update: Update, context: CallbackContext):
37-
msg = update.message.reply_text(
41+
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
42+
await update.message.reply_text(
3843
"Hola, ¿qué tal? ¡Mandame /help si no sabés qué puedo hacer!",
3944
quote=False)
4045

4146

42-
def help(update: Update, context: CallbackContext):
47+
async def help(update: Update, context: ContextTypes.DEFAULT_TYPE):
4348
message_text = ""
4449
session = Session()
4550
try:
@@ -48,14 +53,14 @@ def help(update: Update, context: CallbackContext):
4853
message_text += "/" + command.name + " - " + command.description + "\n"
4954
finally:
5055
session.close()
51-
msg = update.message.reply_text(message_text, quote=False)
56+
await update.message.reply_text(message_text, quote=False)
5257

5358

54-
def estasvivo(update: Update, context: CallbackContext):
55-
msg = update.message.reply_text("Sí, estoy vivo.", quote=False)
59+
async def estasvivo(update: Update, context: ContextTypes.DEFAULT_TYPE):
60+
await update.message.reply_text("Sí, estoy vivo.", quote=False)
5661

5762

58-
def list_buttons(update: Update, context: CallbackContext, listable_type):
63+
async def list_buttons(update: Update, context: ContextTypes.DEFAULT_TYPE, listable_type):
5964
session = Session()
6065
try:
6166
buttons = session.query(listable_type).filter_by(validated=True).order_by(listable_type.name).all()
@@ -68,48 +73,48 @@ def list_buttons(update: Update, context: CallbackContext, listable_type):
6873

6974
keyboard.append(row)
7075
reply_markup = InlineKeyboardMarkup(keyboard)
71-
msg = update.message.reply_text(text="Grupos: ", disable_web_page_preview=True,
76+
await update.message.reply_text(text="Grupos: ", disable_web_page_preview=True,
7277
reply_markup=reply_markup, quote=False)
7378
finally:
7479
session.close()
7580

7681

77-
def listar(update: Update, context: CallbackContext):
78-
list_buttons(update, context, Grupo)
82+
async def listar(update: Update, context: ContextTypes.DEFAULT_TYPE):
83+
await list_buttons(update, context, Grupo)
7984

8085

81-
def listaroptativa(update: Update, context: CallbackContext):
82-
list_buttons(update, context, GrupoOptativa)
86+
async def listaroptativa(update: Update, context: ContextTypes.DEFAULT_TYPE):
87+
await list_buttons(update, context, GrupoOptativa)
8388

8489

85-
def listareci(update: Update, context: CallbackContext):
86-
list_buttons(update, context, ECI)
90+
async def listareci(update: Update, context: ContextTypes.DEFAULT_TYPE):
91+
await list_buttons(update, context, ECI)
8792

8893

89-
def listarotro(update: Update, context: CallbackContext):
90-
list_buttons(update, context, GrupoOtros)
94+
async def listarotro(update: Update, context: ContextTypes.DEFAULT_TYPE):
95+
await list_buttons(update, context, GrupoOtros)
9196

9297

93-
def cubawiki(update: Update, context: CallbackContext):
98+
async def cubawiki(update: Update, context: ContextTypes.DEFAULT_TYPE):
9499
session = Session()
95100
try:
96101
group = session.query(Obligatoria).filter(
97102
Obligatoria.chat_id == str(update.message.chat.id),
98103
Obligatoria.cubawiki_url != None
99104
).first()
100105
if group:
101-
msg = update.message.reply_text(group.cubawiki_url, quote=False)
106+
await update.message.reply_text(group.cubawiki_url, quote=False)
102107
finally:
103108
session.close()
104109

105110

106-
def suggest_listable(update: Update, context: CallbackContext, listable_type):
111+
async def suggest_listable(update: Update, context: ContextTypes.DEFAULT_TYPE, listable_type):
107112
try:
108113
name, url = " ".join(context.args).split("|")
109114
if not (name and url):
110115
raise Exception("not userneim")
111116
except Exception:
112-
msg = update.message.reply_text("Hiciste algo mal, la idea es que pongas:\n" +
117+
await update.message.reply_text("Hiciste algo mal, la idea es que pongas:\n" +
113118
update.message.text.split()[0] +
114119
" <nombre>|<link>",
115120
quote=False)
@@ -133,112 +138,112 @@ def suggest_listable(update: Update, context: CallbackContext, listable_type):
133138
]
134139
]
135140
reply_markup = InlineKeyboardMarkup(keyboard)
136-
context.bot.sendMessage(chat_id=ROZEN_CHATID,
141+
await context.bot.send_message(chat_id=ROZEN_CHATID,
137142
text=listable_type.__name__ + ": " + name + "\n" + url,
138143
reply_markup=reply_markup)
139-
msg = update.message.reply_text("OK, se lo mando a Rozen.", quote=False)
144+
await update.message.reply_text("OK, se lo mando a Rozen.", quote=False)
140145

141146

142-
def sugerirgrupo(update: Update, context: CallbackContext):
143-
suggest_listable(update, context, Obligatoria)
147+
async def sugerirgrupo(update: Update, context: ContextTypes.DEFAULT_TYPE):
148+
await suggest_listable(update, context, Obligatoria)
144149

145150

146-
def sugeriroptativa(update: Update, context: CallbackContext):
147-
suggest_listable(update, context, Optativa)
151+
async def sugeriroptativa(update: Update, context: ContextTypes.DEFAULT_TYPE):
152+
await suggest_listable(update, context, Optativa)
148153

149154

150-
def sugerireci(update: Update, context: CallbackContext):
151-
suggest_listable(update, context, ECI)
155+
async def sugerireci(update: Update, context: ContextTypes.DEFAULT_TYPE):
156+
await suggest_listable(update, context, ECI)
152157

153158

154-
def sugerirotro(update: Update, context: CallbackContext):
155-
suggest_listable(update, context, Otro)
159+
async def sugerirotro(update: Update, context: ContextTypes.DEFAULT_TYPE):
160+
await suggest_listable(update, context, Otro)
156161

157-
def campusvivo(update: Update, context: CallbackContext):
158-
msg = update.message.reply_text("Bancá que me fijo...", quote=False)
162+
async def campusvivo(update: Update, context: ContextTypes.DEFAULT_TYPE):
163+
msg = await update.message.reply_text("Bancá que me fijo...", quote=False)
159164

160165
campus_response_text = is_campus_up()
161166

162-
context.bot.editMessageText(chat_id=msg.chat_id,
167+
await context.bot.edit_message_text(chat_id=msg.chat_id,
163168
message_id=msg.message_id,
164169
text=msg.text + "\n" + campus_response_text)
165170

166171

167-
def flan(update: Update, context: CallbackContext):
168-
responder_imagen(update, context, 'files/Plandeestudios-23.png')
172+
async def flan(update: Update, context: ContextTypes.DEFAULT_TYPE):
173+
await responder_imagen(update, context, 'files/Plandeestudios-23.png')
169174

170-
def flanviejo(update: Update, context: CallbackContext):
171-
responder_imagen(update, context, 'files/Plandeestudios-93.png')
175+
async def flanviejo(update: Update, context: ContextTypes.DEFAULT_TYPE):
176+
await responder_imagen(update, context, 'files/Plandeestudios-93.png')
172177

173-
def aulas(update: Update, context: CallbackContext):
174-
responder_documento(update, context, 'files/0I-aulas.pdf')
178+
async def aulas(update: Update, context: ContextTypes.DEFAULT_TYPE):
179+
await responder_documento(update, context, 'files/0I-aulas.pdf')
175180

176-
def checodepers(update: Update, context: CallbackContext):
181+
async def checodepers(update: Update, context: ContextTypes.DEFAULT_TYPE):
177182
if not context.args:
178183
ejemplo = """ Ejemplo de uso:
179184
/checodepers Hola, tengo un mensaje mucho muy importante que me gustaria que respondan
180185
"""
181-
msg = update.message.reply_text(ejemplo, quote=False)
186+
await update.message.reply_text(ejemplo, quote=False)
182187
return
183188
user = update.message.from_user
184189
try:
185190
if not user.username:
186191
raise Exception("not userneim")
187192
message = " ".join(context.args)
188-
context.bot.sendMessage(
193+
await context.bot.send_message(
189194
chat_id=CODEPERS_CHATID, text=f"{user.first_name}(@{user.username}) : {message}")
190195
except Exception:
191196
try:
192-
context.bot.forward_message(
197+
await context.bot.forward_message(
193198
CODEPERS_CHATID, update.message.chat_id, update.message.message_id)
194199
logger.info(f"Malio sal {str(user)}")
195200
except Exception as e:
196-
update.message.reply_text(
201+
await update.message.reply_text(
197202
"La verdad me re rompí, avisale a roz asi ve que onda", quote=False)
198203
logger.error(e)
199204
return
200-
msg = update.message.reply_text(
205+
await update.message.reply_text(
201206
"OK, se lo mando a les codepers.", quote=False)
202207

203208

204-
def checodeppers(update: Update, context: CallbackContext):
205-
checodepers(update, context)
209+
async def checodeppers(update: Update, context: ContextTypes.DEFAULT_TYPE):
210+
await checodepers(update, context)
206211

207-
def cuandovence(update: Update, context: CallbackContext):
212+
async def cuandovence(update: Update, context: ContextTypes.DEFAULT_TYPE):
208213
ejemplo = "\nCuatris: 1c, 2c, i, inv, invierno, v, ver, verano.\nEjemplo: /cuandovence verano2010"
209214
if not context.args:
210215
ayuda = "Pasame cuatri y año en que aprobaste los TPs." + ejemplo
211-
msg = update.message.reply_text(ayuda, quote=False)
216+
await update.message.reply_text(ayuda, quote=False)
212217
return
213218
try:
214219
linea_entrada = "".join(context.args).lower()
215220
cuatri, anio = parse_cuatri_y_anio(linea_entrada)
216221
except Exception:
217-
msg = update.message.reply_text(
222+
await update.message.reply_text(
218223
"¿Me pasás las cosas bien? Es cuatri+año." + ejemplo, quote=False)
219224
return
220225

221226
vencimiento = calcular_vencimiento(cuatri, anio)
222-
msg = update.message.reply_text(
227+
await update.message.reply_text(
223228
vencimiento, quote=False, parse_mode=ParseMode.MARKDOWN,disable_web_page_preview=True)
224229

225230

226-
def colaborar(update: Update, context: CallbackContext):
227-
msg = update.message.reply_text(
231+
async def colaborar(update: Update, context: ContextTypes.DEFAULT_TYPE):
232+
await update.message.reply_text(
228233
"Se puede colaborar con el DCUBA bot en https://github.com/comcomUBA/dcubabot", quote=False)
229234

230235
# Manda una imagen a partir de su path al chat del update dado
231-
def mandar_imagen(chat_id, context: CallbackContext, file_path):
232-
context.bot.sendChatAction(chat_id=chat_id, action=ChatAction.UPLOAD_PHOTO)
236+
async def mandar_imagen(chat_id, context: ContextTypes.DEFAULT_TYPE, file_path):
237+
await context.bot.send_chat_action(chat_id=chat_id, action=ChatAction.UPLOAD_PHOTO)
233238
session = Session()
234239
try:
235240
file = session.query(File).filter_by(path=file_path).first()
236241
if file:
237-
msg = context.bot.send_photo(
242+
msg = await context.bot.send_photo(
238243
chat_id=chat_id, photo=file.file_id, allow_sending_without_reply=True)
239244
else:
240245
with open(file_path, 'rb') as f:
241-
msg = context.bot.send_photo(
246+
msg = await context.bot.send_photo(
242247
chat_id=chat_id, photo=f, allow_sending_without_reply=True)
243248
new_file = File(path=file_path, file_id=msg.photo[0].file_id)
244249
session.add(new_file)
@@ -248,18 +253,18 @@ def mandar_imagen(chat_id, context: CallbackContext, file_path):
248253

249254

250255
# Manda un documento a partir de su path al chat del update dado
251-
def mandar_pdf(chat_id, context: CallbackContext, file_path):
252-
context.bot.sendChatAction(
256+
async def mandar_pdf(chat_id, context: ContextTypes.DEFAULT_TYPE, file_path):
257+
await context.bot.send_chat_action(
253258
chat_id=chat_id, action=ChatAction.UPLOAD_DOCUMENT)
254259
session = Session()
255260
try:
256261
file = session.query(File).filter_by(path=file_path).first()
257262
if file:
258-
msg = context.bot.send_document(
263+
msg = await context.bot.send_document(
259264
chat_id=chat_id, document=file.file_id, allow_sending_without_reply=True)
260265
else:
261266
with open(file_path, 'rb') as f:
262-
msg = context.bot.send_document(
267+
msg = await context.bot.send_document(
263268
chat_id=chat_id, document=f, allow_sending_without_reply=True)
264269
new_file = File(path=file_path, file_id=msg.document.file_id)
265270
session.add(new_file)
@@ -269,12 +274,12 @@ def mandar_pdf(chat_id, context: CallbackContext, file_path):
269274

270275

271276
# Responde una imagen a partir de su path al chat del update dado
272-
def responder_imagen(update: Update, context: CallbackContext, file_path):
273-
mandar_imagen(update.message.chat_id, context, file_path)
277+
async def responder_imagen(update: Update, context: ContextTypes.DEFAULT_TYPE, file_path):
278+
await mandar_imagen(update.message.chat_id, context, file_path)
274279

275280
# Responde un documento a partir de su path al chat del update dado
276-
def responder_documento(update: Update, context: CallbackContext, file_path):
277-
mandar_pdf(update.message.chat_id, context, file_path)
281+
async def responder_documento(update: Update, context: ContextTypes.DEFAULT_TYPE, file_path):
282+
await mandar_pdf(update.message.chat_id, context, file_path)
278283

279284

280285
COMMANDS = {

main.py

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,28 @@
11
import telegram
22
import os
3-
from telegram.ext import Updater, CommandHandler
3+
from telegram.ext import Application, CommandHandler
44
from bot_logic import COMMANDS
55
from models import init_db
66

77
def main():
88
"""Start the bot."""
9-
# Create the Updater and pass it your bot's token.
10-
updater = Updater(os.environ["TELEGRAM_BOT_TOKEN"])
11-
12-
# Get the dispatcher to register handlers
13-
dispatcher = updater.dispatcher
9+
# Create the Application and pass it your bot's token.
10+
application = Application.builder().token(os.environ["TELEGRAM_BOT_TOKEN"]).build()
1411

1512
# on different commands - answer in Telegram
1613
for command_name, command_handler in COMMANDS.items():
17-
dispatcher.add_handler(CommandHandler(command_name, command_handler))
14+
application.add_handler(CommandHandler(command_name, command_handler))
1815

1916
# Initialize the database
2017
init_db()
2118

2219
# Start the Bot
23-
updater.start_webhook(listen="0.0.0.0",
24-
port=int(os.environ.get('PORT', 8080)),
25-
url_path=os.environ["TELEGRAM_BOT_TOKEN"])
26-
#updater.bot.setWebhook('https://' + os.environ['HEROKU_APP_NAME'] + '.herokuapp.com/' + os.environ["TELEGRAM_BOT_TOKEN"])
27-
28-
# Run the bot until you press Ctrl-C or the process receives SIGINT,
29-
# SIGTERM or SIGABRT. This should be used most of the time, since
30-
# start_polling() is non-blocking and will stop the bot gracefully.
31-
updater.idle()
20+
application.run_webhook(
21+
listen="0.0.0.0",
22+
port=int(os.environ.get("PORT", 8080)),
23+
url_path=os.environ["TELEGRAM_BOT_TOKEN"],
24+
#webhook_url='https://' + os.environ['HEROKU_APP_NAME'] + '.herokuapp.com/' + os.environ["TELEGRAM_BOT_TOKEN"]
25+
)
3226

3327
if __name__ == "__main__":
3428
main()

requirements.txt

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
11
icalevents
22
pytz
33
requests
4-
python_telegram_bot==13.11
4+
python-telegram-bot==22.0
55
robobrowser==0.5.3
6-
Werkzeug==0.15.5
7-
Flask
8-
MarkupSafe==2.0.1
96
psycopg2-binary
107
SQLAlchemy
118
sqlalchemy-cockroachdb

0 commit comments

Comments
 (0)