Browse Source

upgrade syntax to last python-telegram-bot version

lucacolombogomez 4 years ago
parent
commit
ba5498803a
3 changed files with 42 additions and 42 deletions
  1. 11 6
      LCMbot.py
  2. 19 13
      handlers.py
  3. 12 23
      tale_handler.py

+ 11 - 6
LCMbot.py

@@ -1,38 +1,43 @@
+#!/usr/bin/env python
 # -*- coding: utf-8 -*-
 from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters,
                           CallbackQueryHandler)
 import handlers as hnd
 from tale_handler import TaleHandler
 
+import logging
+logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
+                     level=logging.INFO)
 
 def main():
     # create LCMbot
-    updater = Updater('TOKEN')
+    updater = Updater('TOKEN',use_context=True)
     dp = updater.dispatcher
 
     # register handlers
+    dp.add_handler(CommandHandler('start',hnd.start))
     dp.add_handler(CommandHandler('pinglcm', hnd.ping))
     dp.add_handler(CommandHandler('checkwebsite', hnd.is_web_up))
     dp.add_handler(CommandHandler('vietnam', hnd.vietnam))
     dp.add_handler(CommandHandler('sellyourmother', hnd.sell_your_mother))
     dp.add_handler(CommandHandler('abuse150', hnd.abuse_150))
     dp.add_handler(CommandHandler('rndwisdom', hnd.speak, pass_args=True))
+    dp.add_handler(CommandHandler('moarpuddu', hnd.moarpuddu))
 
     tale_handler = TaleHandler()
     dp.add_handler(CommandHandler('addatale', tale_handler.prompt_user))
-    dp.add_handler(MessageHandler([Filters.text], tale_handler.handle_new_tale))
+    dp.add_handler(MessageHandler(Filters.text, tale_handler.handle_new_tale))
     dp.add_handler(CallbackQueryHandler(tale_handler.save_tale))
     dp.add_handler(CommandHandler('tellatale', tale_handler.tell_a_tale))
 
-    dp.add_error_handler(hnd.error)
+    # dp.add_error_handler(hnd.error)
     # dp.add_handler(MessageHandler([], hnd.print_msg_info))
 
-    # start LCMbot
+    # start  LCMbot
     updater.start_polling()
 
-    # run until the process receives SIGINT, SIGTERM or SIGABRT
+    # make bot process responsive to SIGINT, SIGTERM or SIGABRT
     updater.idle()
 
-
 if __name__ == '__main__':
     main()

+ 19 - 13
handlers.py

@@ -4,13 +4,14 @@ import httplib
 import numpy as np
 from insults import insults
 from speak import produce_sentence
-import logging
-# enable logging
-fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
-logging.basicConfig(format=fmt, level=logging.INFO)
 
 
-def ping(bot, update):
+def start(update, context):
+    """Says hi to new users"""
+    #context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!")
+    update.message.reply_text(text='Bot ufficiale di LCM')
+
+def ping(update, context):
     """Check LCM ping response"""
     try:
         sp.check_output(['ping', '-c', '1', 'lcm.mi.infn.it'])
@@ -19,7 +20,7 @@ def ping(bot, update):
     update.message.reply_text(text='LCM is reachable')
 
 
-def is_web_up(bot, update):
+def is_web_up(update, context):
     """Check LCM http response"""
     try:
         conn = httplib.HTTPConnection('lcm.mi.infn.it:443')
@@ -30,39 +31,44 @@ def is_web_up(bot, update):
         update.message.reply_text(text='An error occurred while connecting')
 
 
-def vietnam(bot, update):
+def vietnam(update, context):
     """Spout wise words"""
     update.message.reply_text(text='Ricordate, ragazzi, LCM è come il Vietnam. '
                               'Una volta entrati, è impossibile uscirne!',
                               quote=False)
 
 
-def sell_your_mother(bot, update):
+def sell_your_mother(update, context):
     """Remind people not to disclose passwords"""
-    pic_id = 'AgADBAADbasxG9JPlAQNlEW3ML5sk_bEXxkABHKAFZ1ZzBZsNvMBAAEC'
+    pic_id = 'AgADBAAD4LExG98F2FMjGW6Jx6z07T2OtxsABAEAAwIAA3gAA6eOAAIWBA'
     update.message.reply_photo(photo=pic_id, caption='cit. Mandelli',
                                quote=False)
 
 
-def print_msg_info(bot, update):
+def print_msg_info(update, context):
     """Print all message info to console - useful for debugging purposes"""
     print update.message
 
 
-def error(bot, update, error):
+def error(update, context, error):
     """Log errors"""
     # create a logger with function scope ("static" object)
     error.logger = logging.getLogger(__name__)
     error.logger.warn('Update "%s" caused error "%s"' % (update, error))
 
 
-def abuse_150(bot, update):
+def abuse_150(update, context):
     """Verbally abuse incompetent LCM collaborators"""
     insult = np.random.choice(insults)
     update.message.reply_text(text=insult, quote=False)
 
 
-def speak(bot, update, args):
+def moarpuddu(bot, update):
+    """More broken pipes for Puddu"""
+    update.message.reply_text(text="più broken pipe per Puddu", quote=False)
+
+
+def speak(update, context, *args):
     """Produce pseudo-random wise words"""
     word = args[0] if len(args) > 0 else None
     update.message.reply_text(text=produce_sentence(word), quote=False)

+ 12 - 23
tale_handler.py

@@ -22,13 +22,13 @@ class TaleHandler:
         self.cur_authors = [] # list of tuples (user_id, prompt_msg_id)
         self.cur_tales = [] # list of Tale objects (tales to be added to db)
 
-    def prompt_user(self, bot, update):
+    def prompt_user(self, update, context):
         """Prompt user to tell a tale. It will be added to database if upvoted
         at least three times
         """
-        if update.message.chat.type != Chat.GROUP:
-            update.message.reply_text(text='We need to be in a group chat to '
-                                           'add a new tale or anecdote!')
+        ctype=update.message.chat.type
+        if update.message.chat.type != Chat.GROUP and update.message.chat.type != Chat.SUPERGROUP :
+            update.message.reply_text(text='You need to be in the official LCM group chat to add a new tale or anecdote!')
             return
         user = update.message.from_user
         prompt_msg = update.message.reply_text(
@@ -36,7 +36,7 @@ class TaleHandler:
             reply_markup=ForceReply(selective=True))
         self.cur_authors.append((user.id, prompt_msg.message_id))
 
-    def handle_new_tale(self, bot, update):
+    def handle_new_tale(self, update, context):
         """Start the upvoting procedure when a new tale is received"""
         tale_msg = update.message
         author = tale_msg.from_user
@@ -59,7 +59,7 @@ class TaleHandler:
           text='Alright, I need three upvotes to add this tale to my database',
           reply_markup=keyboard)
 
-    def save_tale(self, bot, update):
+    def save_tale(self, update, context):
         """Add tale to db when upvoted three times"""
         query = update.callback_query
         voter = query.from_user
@@ -73,37 +73,26 @@ class TaleHandler:
 
         if voter.id == t.author.id:
             # authors cannot upvote their own story
-            bot.answer_callback_query(
-                callback_query_id=query.id,
-                text="Nope, can't upvote your own tale")
+            query.answer(text="Nope, can't upvote your own tale")
         elif voter.id in t.upvoters_id:
-            bot.answer_callback_query(
-                callback_query_id=query.id,
-                text='One upvote per person, sorry')
+            query.answer(text='One upvote per person, sorry')
         else:
             t.upvoters_id.append(voter.id)
             t.upvotes += 1
-            bot.answer_callback_query(
-                callback_query_id=query.id,
-                text='Upvote registered')
+            query.answer(text='Upvote registered')
             if t.upvotes == 3:
                 n_tale = self.db.incr('n_tales')
                 self.db.hset(str(n_tale), 'author', t.author.first_name)
                 self.db.hset(str(n_tale), 'tale', t.text)
-                bot.editMessageText(chat_id=query.message.chat_id,
-                                    message_id=query.message.message_id,
-                                    text='Tale saved to database')
+                query.edit_message_text(text='Tale saved to database')
             else:
                 thumb_up = u'\U0001F44D'
                 button = InlineKeyboardButton(thumb_up + str(t.upvotes),
                                               callback_data=query.data)
                 keyboard = InlineKeyboardMarkup([[button]])
-                bot.editMessageText(chat_id=query.message.chat_id,
-                                    message_id=query.message.message_id,
-                                    text=query.message.text,
-                                    reply_markup=keyboard)
+                query.edit_message_text(text=query.message.text,reply_markup=keyboard)
 
-    def tell_a_tale(self, bot, update):
+    def tell_a_tale(self, update, context):
 	"""Tell a tale about LCM"""
         msg = update.message
         n_tales = self.db.get('n_tales')