예제 #1
0
async def on_callback_query(data):
    query_id, from_id, query_data = telepot.glance(data,
                                                   flavor="callback_query")

    if not ManagerClients.existClient(from_id):
        if query_data in ["TermoServicoAceito", "TermoServicoNaoAceito"]:
            if query_data == "TermoServicoAceito":
                await bot.answerCallbackQuery(query_id,
                                              text="Aguarde um momento...")
                edited = telepot.message_identifier(data["message"])
                await bot.editMessageText(edited,
                                          "Você aceitou o termo de serviço.")

                firstname_inline = KeyboardButton(
                    text=data["from"]
                    ["first_name"]) if "first_name" in data["from"] else None
                username_inline = KeyboardButton(
                    text=data["from"]
                    ["username"]) if "username" in data["from"] else None
                keyboard = []
                if firstname_inline: keyboard.append([firstname_inline])
                if username_inline: keyboard.append([username_inline])

                keyboard = ReplyKeyboardMarkup(keyboard=keyboard,
                                               resize_keyboard=True)
                whats_name = await bot.sendMessage(
                    from_id,
                    "Como gostaria de si chamar?\nEscolha uma das opções abaixo ou digite outra.",
                    reply_markup=keyboard)
                ManagerClients.createClient(from_id, whats_name["message_id"])
            else:
                edited = telepot.message_identifier(data["message"])
                await bot.editMessageText(
                    edited, "Você não aceitou o termo de serviço.")
예제 #2
0
파일: state.py 프로젝트: esdandreu/WakePi
 def refresh_dashboard(self):
     '''Deletes last message and sends a new one'''
     msg_text = self.get_msg_text()
     tries = 0
     chat_count = 0
     for chat_id in self.chat_id_list:
         '''Sends the message with dashboard and the message with custom keyboard
            to every allowed chat id
            '''
         while tries < 2:
             try:
                 dashboard = self.dashboard()
                 keyboard = self.keyboard()
                 dash_msg_id = self.bot.sendMessage(chat_id,
                                                    msg_text,
                                                    parse_mode='Markdown',
                                                    reply_markup=dashboard)
                 reply_msg_id = self.bot.sendMessage(chat_id,
                                                     self.reply_text,
                                                     parse_mode='Markdown',
                                                     reply_markup=keyboard)
                 self.delete_last_msg(self.bot, chat_count)
                 self.set_reply_text('')
                 self.store_dash_msg(
                     chat_count, telepot.message_identifier(dash_msg_id))
                 self.store_reply_msg(
                     chat_count, telepot.message_identifier(reply_msg_id))
                 logger.info('Refresh')
                 break
             except Exception as error:
                 tries = tries + 1
                 logger.error("Could not refresh: {}\n {}".format(
                     sys._getframe().f_code.co_name, error))
         chat_count += 1
     return
예제 #3
0
 def callback_response(self, callback):
     reply_markup = None
     if self.response:
         if len(self.response) == 3:
             # Only if it needs to replace a button
             self.replaceable_button(buttons=self.response[2][0], condition=self.response[2][1])
             # return just inline key board
         reply_markup = self.make_inline_keyboard()
     if isinstance(self.response[0], str):
         # send a message to user (above inline buttons)
         try:
             TelePot.editMessageText((telepot.message_identifier(msg=callback['message'])),
                                     text=self.response[0],
                                     reply_markup=reply_markup)
         except telepot.exception.TelegramError:
             # self.inline_message = self.response[0]
             pass
     elif isinstance(self.response[0], types.FunctionType):
         # send a message below inline buttons
         TelePot.sendMessage(self.user.telegram.chat_id,
                                        text=self.response[0]())
     elif reply_markup:
         # send a key board to user
         TelePot.editMessageReplyMarkup(telepot.message_identifier(msg=callback['message']),
                                        reply_markup=reply_markup)
     if self.inline_message:
         # send an inline message
         TelePot.answerCallbackQuery(callback['id'],
                                     text=self.inline_message)
예제 #4
0
    async def delete_data(self, event, _list, _id):
        obj = next((x for x in _list if int(x['id']) == int(_id)), None)

        if obj != None:
            obj['status'] = _('ended')

            for msg in obj['messages']:
                if 'status' in obj:
                    await self.bot.editMessageText(
                        telepot.message_identifier(msg),
                        self.create_list(obj),
                        parse_mode="markdown")
                else:
                    await self.bot.editMessageText(
                        telepot.message_identifier(msg),
                        self.create_quest(obj),
                        parse_mode="markdown")

            i = 0
            for x in _list:
                if int(x['id']) == int(_id):
                    _list.pop(i)
                    self.persist_data()
                    break
                else:
                    i += 1
예제 #5
0
def on_chat_message(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    if str(chat_id) == auth_chat:
        #用户ID
        members_id = msg['from']['id']
        if content_type == 'new_chat_member':
            #新用户列表
            global user_list
            #用户昵称
            new_members_name = msg['from']['first_name']
            #限制新入群成员所有权限
            bot.restrictChatMember(chat_id, members_id, until_date=None)
            #删除入群消息
            bot.deleteMessage(telepot.message_identifier(msg))
            #验证码字段
            gcc = get_chinese_captcha(4)
            #生成随机验证码并打乱排序
            bkg = bulid_kb(gcc)
            #验证码输入模块
            keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [InlineKeyboardButton(text=bkg[0][0], callback_data='0')],
                [InlineKeyboardButton(text=bkg[0][1], callback_data='1')],
                [InlineKeyboardButton(text=bkg[0][2], callback_data='2')],
                [InlineKeyboardButton(text=bkg[0][3], callback_data='3')]
            ])
            #发送验证码图片
            sp = bot.sendPhoto(
                chat_id,
                bulid_captcha(gcc),
                caption=
                '[%s](tg://user?id=%s)\n请在 *90秒* 内选择下方与图片一致的验证码,否则将会被 *永久封禁* 。\n你只有2次机会。'
                % (uname_DS(new_members_name), members_id),
                disable_notification=True,
                parse_mode='Markdown',
                reply_markup=keyboard)
            #加到新用户列表
            user_list.append(members_id)  #加到list
            #添加到redis,并设置自动销毁时间为110秒。
            id_count.rpush(members_id, bkg[1], sp['message_id'])
            id_count.expire(members_id, 110)
        elif content_type == 'left_chat_member':
            #删除退群信息
            bot.deleteMessage(telepot.message_identifier(msg))
            cc_code = id_count.lrange(members_id, 0, -1)
            #未完成流程就退出群组,封锁掉。
            if cc_code != None:
                try:
                    bot.deleteMessage(
                        (auth_chat,
                         int(
                             id_count.lrange(members_id, 0,
                                             -1)[1].decode('utf-8'))))
                    id_count.delete(members_id)
                    bot.kickChatMember(auth_chat, members_id)
                    user_list.remove(members_id)
                except:
                    pass
    elif auth_chat == '':
        print('本群组ID为: ' + str(chat_id))
예제 #6
0
def on_callback_query(msg):
    query_id, from_id, data = telepot.glance(msg, flavor='callback_query')
    print('Callback query:', query_id, from_id, data)

    global message_with_inline_keyboard
    if data == 'servers':
        make_makup()
        markup = InlineKeyboardMarkup(inline_keyboard=servers)
        bot.editMessageText(
            telepot.message_identifier(message_with_inline_keyboard),
            'SERVER IP | PING | REGION',
            reply_markup=markup)

    elif data == 'back':
        markup = InlineKeyboardMarkup(inline_keyboard=[
            [
                dict(text='Refresh', callback_data='refresh'),
                dict(text='Servers', callback_data='servers')
            ],
        ])
        bot.editMessageText(
            telepot.message_identifier(message_with_inline_keyboard),
            'Hi, choose Refresh to update the servers online,or Servers to get them',
            reply_markup=markup)
    elif data == 'refresh':
        if refresh_servers() == True:
            markup = InlineKeyboardMarkup(inline_keyboard=[
                [dict(text='Servers', callback_data='servers')],
            ])
            bot.editMessageText(
                telepot.message_identifier(message_with_inline_keyboard),
                'Server list updated',
                reply_markup=markup)
    elif data == 'disconnect':
        os.system('sudo killall lan-play-linux')
        markup = InlineKeyboardMarkup(inline_keyboard=[
            [dict(text='Servers', callback_data='servers')],
        ])
        bot.editMessageText(
            telepot.message_identifier(message_with_inline_keyboard),
            'Disconnected',
            reply_markup=markup)
    else:
        markup = InlineKeyboardMarkup(inline_keyboard=[
            [
                dict(text='Disconnect', callback_data='disconnect'),
                dict(text='Servers', callback_data='servers')
            ],
        ])

        subprocess.Popen(
            ["sudo ./lan-play-linux --relay-server-addr {0}".format(data)],
            stdout=subprocess.PIPE,
            stderr=None,
            shell=True)
        bot.editMessageText(
            telepot.message_identifier(message_with_inline_keyboard),
            'You are connected',
            reply_markup=markup)
예제 #7
0
파일: bot.py 프로젝트: Kermitofx/Listask
def on_callback_query(msg):
    query_id, from_id, data = telepot.glance(msg, flavor='callback_query')
    print('Callback query:', query_id, from_id, data)
    if data == 'n':
        bot.answerCallbackQuery(query_id, text='estou ativo!')

    elif data == 'edit':
        global message_with_inline_keyboard
        if message_with_inline_keyboard:
            msg_idf = telepot.message_identifier(message_with_inline_keyboard)
            markup = InlineKeyboardMarkup(inline_keyboard=[
                [dict(text='🔧suporte', url='https://telegram.me/odouspam')],
                [InlineKeyboardButton(text='📃status', callback_data='n')] +
                [InlineKeyboardButton(text='⚙', callback_data=' ')] +
                [InlineKeyboardButton(text='ℹinfo', callback_data='info')]
            ])

            bot.editMessageText(msg_idf,
                                '''
rs, meus comandos desponíveis😊👇
*lista* - envia a lista de canais disponíveis.
*menu* - menu extra.

ultilize /<comando> para ultilizar o comando desejado.
EXEMPLO: */lista*''',
                                parse_mode="Markdown",
                                reply_markup=markup)
    elif data == 'info':
        a = bot.getMe()
        n = a['first_name']
        u = a['username']
        global message_with_inline_keyboard
        if message_with_inline_keyboard:
            msg_idf = telepot.message_identifier(message_with_inline_keyboard)
            markup = InlineKeyboardMarkup(inline_keyboard=[
                [dict(text='🔧suporte', url='https://telegram.me/Odouspam')],
                [InlineKeyboardButton(text='📃status', callback_data='n')] +
                [InlineKeyboardButton(text='⚙Comandos', callback_data='edit')
                 ] + [InlineKeyboardButton(text='ℹ', callback_data=' ')]
            ])
            bot.editMessageText(msg_idf,
                                '''
🤖*Informações do bot:*
➖➖➖➖➖➖➖➖➖
*bot*: `{}`

*username:*` {}`
➖➖➖➖
[Criador](https://telegram.me/Odouspam) '''.format(n, u),
                                disable_web_page_preview=True,
                                parse_mode="Markdown",
                                reply_markup=markup)

        else:
            bot.answerCallbackQuery(
                query_id, text='Ops! ocorreu um bug! tente /start....')
예제 #8
0
def on_callback_query(msg):
    print("!")
    print("hello", msg)
    if msg["data"][:6] == "yuhuha":
        yuhuma_list.append([int(msg["data"].split()[1]), int(msg["data"].split()[2])])
        skull_bot.deleteMessage(telepot.message_identifier(msg["message"]))
    elif msg["data"][:4] == "card":
        print(msg["data"])
        card_list.append(eval(msg["data"][4:]))
        skull_bot.deleteMessage(telepot.message_identifier(msg["message"]))
예제 #9
0
  def on_chat_message(self, msg): 
    content_type, chat_type, chat_id = telepot.glance(msg) 
    # check valid user
    if not self.db.isUser(chat_id):
      self.sender.sendMessage('user_id: %d is not a valid user' % (chat_id))
      return 
    
    # always consider text message
    if content_type == 'text': 
      # command - progress
      if msg['text'] == '/progress':
        self.mode = 'progress'
        self.showTorrentsProgress() 
        return

      # command - delete
      elif msg['text'] == '/delete':
        self.mode = 'delete'
        # clear message identifier saved
        if self.edtTorrents:
          id = telepot.message_identifier(self.edtTorrents)
          self.bot.editMessageText(id, '...', reply_markup=None)

        self.sender.sendMessage('Select torrent to delete ...')
        self.torrents = self.ongoingList()
        if len(self.torrents) == 0: 
          self.sender.sendMessage('There is no downloading files.')
          self.edtTorrents = None
        else:
          self.showTorrentsMenu(self.torrents) 

      # command - reboot
      elif msg['text'] == '/reboot':
  	  	self.sender.sendMessage('Torrent server rebooting ...')
  	  	self.sender.sendMessage('*** Do not enter message ***')
    		self.server.reboot()
  	  	self.sender.sendMessage('System ok ...')

      # search torrents file using self.search function
      else: 
        self.mode = 'search'
        if self.edtTorrents:
          id = telepot.message_identifier(self.edtTorrents)
          self.bot.editMessageText(id, '...', reply_markup=None)

        self.sender.sendMessage('searching ...') 
        self.torrents = self.search(unicode(msg['text'])) 

        if not len(self.torrents): 
          self.sender.sendMessage('There is no files searched.')
          self.edtTorrents = None
        else: 
          self.showTorrentsMenu(self.torrents)

    else: self.sender.sendMessage('You can only send text message.')
예제 #10
0
def on_callback_query(msg):
    query_id, from_id, query_data = telepot.glance(msg,
                                                   flavor='callback_query')
    chat_id = msg['from']['id']
    #query_data contiene il valore callback_data del pulsante premuto

    if query_data.startswith('calendar-day-'):
        saved_date = current_shown_dates.get(chat_id)
        if (saved_date is not None):
            day = query_data[13:]
            date = datetime.date(int(saved_date[0]), int(saved_date[1]),
                                 int(day))
            start_date = str(date) + "T00:00:00." + datetime.datetime.now(
            ).strftime("%S") + 'Z'
            end_date = str(date) + "T23:59:59." + datetime.datetime.now(
            ).strftime("%S") + 'Z'
            message = search_calendar(start_date, end_date)
            bot.sendMessage(chat_id, message, parse_mode='Markdown')
        else:
            bot.sendMessage(chat_id, "Errore! Per favore riprova")

    elif query_data.startswith('next-month'):
        saved_date = current_shown_dates.get(chat_id)
        if (saved_date is not None):
            year, month = saved_date
            month += 1
            if month > 12:
                month = 1
                year += 1
            date = (year, month)
            current_shown_dates[chat_id] = date
            keyboard = create_calendar(year, month)
            #Non viene creata una nuova keyboard con il nuovo mese ma viene aggiornata quella già esistente
            bot.editMessageReplyMarkup(telepot.message_identifier(
                msg['message']),
                                       reply_markup=keyboard)
        else:
            bot.sendMessage(chat_id, "Errore! Per favore riprova")

    elif query_data.startswith('previous-month'):
        saved_date = current_shown_dates.get(chat_id)
        if (saved_date is not None):
            year, month = saved_date
            month -= 1
            if month < 1:
                month = 12
                year -= 1
            date = (year, month)
            current_shown_dates[chat_id] = date
            keyboard = create_calendar(year, month)
            bot.editMessageReplyMarkup(telepot.message_identifier(
                msg['message']),
                                       reply_markup=keyboard)
        else:
            bot.sendMessage(chat_id, "Errore! Per favore riprova")
예제 #11
0
def inline_button_handler(update):
    # שולף את הטקסט של הכפתור - callback_data.
    clicked = get_message_text(update)

    # מחלץ את האינדקס של השיר - איפה הוא ממוקם ב uploaded_list. משמש להמרות עצמן - שולפים את השיר מהקובץ המקורי, יותר נח להתעסק איתו.
    index = clicked.split("|")[1]

    # התו הראשון הוא סימן "+" או "-". אם התו השני הוא "|" אין מספר, נלחץ כפתור "+" או "-", מה שאומר שצריך לעדכן את המקלדת.
    if clicked[1] == "|":

        # אם נלחץ כפתור "+"..
        if clicked[0] == "+":

            try:
                # עורכים את המקלדת של ההודעה המתאימה - למקלדת המרה עם כפתורי ה"+".
                bot.editMessageReplyMarkup(telepot.message_identifier(
                    get_message(update)),
                                           reply_markup=keyboard_plus(index))
            except Exception as e:
                print(e)

            finally:
                # מדווח לטלגרם שהבקשה טופלה בהצלחה.
                bot.answerCallbackQuery(get_query_id(update))
                return

        # אם נלחץ כפתור "+"..
        elif clicked[0] == "-":

            try:
                # עורכים את המקלדת של ההודעה המתאימה - למקלדת המרה עם כפתורי ה"+".
                bot.editMessageReplyMarkup(telepot.message_identifier(
                    get_message(update)),
                                           reply_markup=keyboard_minus(index))

            except Exception as e:
                print(e)

            finally:
                # מדווח לטלגרם שהבקשה טופלה בהצלחה.
                bot.answerCallbackQuery(get_query_id(update))
                return

    # אם הכפתור הוא בקשה להמרה, ממיר את השיר. שומר שוב את easy_key כי צריך אותו ל send_data כדי ליצור את המקלדת הרגילה.
    data, easy_key = new_key(int(index), clicked.split("|")[0])

    # שולח את השיר החדש אחרי ההמרה למשתמש.
    send_data(data, update["callback_query"], True, True, None, easy_key,
              index)

    # מדווח לטלגרם שהבקשה טופלה בהצלחה.
    bot.answerCallbackQuery(get_query_id(update))
    return
예제 #12
0
def on_callback_query(msg):
    query_id, from_id, data = telepot.glance(msg, flavor='callback_query')
    info = 'Callback query: ' + str(query_id) + ', ' + str(
        from_id) + ', ' + str(data)
    logging.info(info)
    global message_with_inline_keyboard
    global markup
    global poll_of_the_day
    global risultati
    try:
        if from_id not in votanti.keys():
            risultati[data] += 1
            votanti[from_id] = data
            bot.answerCallbackQuery(query_id,
                                    text=data + ': ' + str(risultati[data]))
            buttons = []
            for e in risultati.keys():
                buttons.append([
                    InlineKeyboardButton(text=str(e) + ' (' +
                                         str(risultati[e]) + ')',
                                         callback_data=e)
                ])
            markup = InlineKeyboardMarkup(inline_keyboard=buttons)
            msg_idf = telepot.message_identifier(message_with_inline_keyboard)
            bot.editMessageText(msg_idf, poll_of_the_day, reply_markup=markup)
        else:
            if votanti[from_id] == data:
                bot.answerCallbackQuery(query_id,
                                        text=msg['from']['username'] +
                                        ' ha già espresso il suo voto')
            else:
                risultati[data] += 1
                risultati[votanti[from_id]] -= 1
                votanti[from_id] = data
                bot.answerCallbackQuery(query_id,
                                        text=data + ': ' +
                                        str(risultati[data]))
                buttons = []
                for e in risultati.keys():
                    buttons.append([
                        InlineKeyboardButton(text=str(e) + ' (' +
                                             str(risultati[e]) + ')',
                                             callback_data=e)
                    ])
                markup = InlineKeyboardMarkup(inline_keyboard=buttons)
                msg_idf = telepot.message_identifier(
                    message_with_inline_keyboard)
                bot.editMessageText(msg_idf,
                                    poll_of_the_day,
                                    reply_markup=markup)

    except KeyError:
        bot.answerCallbackQuery(query_id, text='Sondaggio chiuso')
예제 #13
0
    async def status_callback(self, wait_msg, current, total):
        if current == total:
            await self.editMessageText(
                telepot.message_identifier(wait_msg),
                '99.%s%%...' % ('9' * random.randint(3, 12)))
            return

        if current > 0 and self.last_msg_edit < time.time() - 2:
            current_pct = current / total * 100
            await self.editMessageText(telepot.message_identifier(wait_msg),
                                       '%.01f%%...' % (current_pct))
            self.last_msg_edit = time.time()
예제 #14
0
def callback(msg):
    query_id, from_id, query_data = telepot.glance(msg,
                                                   flavor='callback_query')
    # for private chats, from_id == chat_id

    print('Callback Query:', query_id, from_id, query_data)
    query_data = query_data.split(";")

    if query_data[0] == 'old':  # user has selected old index
        bot.editMessageText(telepot.message_identifier(msg['message']),
                            "You have selected Index no. " + query_data[1])
        activeUserOldIdx[from_id] = query_data[1]
        listNewIdx(query_data[1], from_id)

    elif query_data[0] == 'new':  # user has selected new index
        bot.editMessageText(
            telepot.message_identifier(msg['message']),
            "You have selected Index no. " + query_data[1] + " to swap into.")
        activeUserNewIdx[from_id] = query_data[1]
        bot.sendMessage(from_id, "Processing...")
        # if email is still validating (I hope not), we stall
        threads[0].join()
        if activeUserEmailCheck[from_id] == False:
            bot.sendMessage(from_id, "Naughty naughty! Further validation has found that your email " + \
                            "address is in fact invalid. This bot will now quit.")
            bot.sendSticker(from_id, "CAADBQADzgADbqRAAn_r6fO8RQf7Ag")
        else:
            sendMsg = "Your request has been entered into our database." + \
                      ".\nWe will notify you once we have found you a match."
            bot.sendSticker(from_id, stickers[random.randrange(0, 3)])
            bot.sendMessage(from_id, sendMsg)
            # database Insert Data
            matchSwapIndex(from_id)
        # Destroy User Session
        destroyUserSession(from_id)

    elif query_data[0] == 'mod':  # user wants to see session details
        sendMsg = listModDataAsText(activeUserModData[from_id])
        inline_kb = [[(InlineKeyboardButton(
            text="Done? Click here to collapse this message",
            callback_data="del;0"))]]
        keyboard = InlineKeyboardMarkup(inline_keyboard=inline_kb)
        bot.sendMessage(from_id, sendMsg, 'markdown', reply_markup=keyboard)

    elif query_data[0] == 'del':  # session details message is collapsible
        bot.deleteMessage(telepot.message_identifier(msg['message']))

    bot.answerCallbackQuery(query_id)
예제 #15
0
    async def on_callback_query(self, msg):
        query_id, from_id, query_data = glance(msg, flavor='callback_query')
        match = None
        try:
            data = self.deserialize(query_data)
            print(data)
            with self.todo_table as table:
                match = table.find_one(rid=data)
                table.delete(rid=data)

            #silently quit if already deleted
            if not match:
                logger.info(
                    'User {} trying to delete non-existent to-do entry with key'
                    .format(data))
                return

            #don't let other users delete your entries
            if from_id != match['uid']:
                logger.info(
                    'User {} trying to delete to-do entry for user {} with key'
                    .format(from_id, match['uid'], match['id']))
                return

            items = await self._get_user_items(from_id)
            if items:
                keyboard = await self._make_keyboard(items)
                await self.bot.editMessageText(message_identifier(
                    msg['message']),
                                               text='.',
                                               reply_markup=keyboard)
                await self.bot.editMessageText(
                    message_identifier(msg['message']),
                    text='TODO list. Click an entry to delete it',
                    reply_markup=keyboard)
            else:
                await self.bot.editMessageText(
                    message_identifier(msg['message']),
                    text='Your to-do list is now empty.')

        #silently except if not this beard's callback data
        except ThatsNotMineException:
            pass

        try:
            super().on_callback_query(msg)
        except AttributeError:
            pass
예제 #16
0
    def main_menu(self):
        try:
            self.bot.editMessageReplyMarkup(self._edit_mgs_ident)
        except:
            pass

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [
                InlineKeyboardButton(text='PULSA & DATA',
                                     callback_data='PULSA'),
            ],
            [
                InlineKeyboardButton(text='GAME ONLINE', callback_data='GAME'),
                InlineKeyboardButton(text='TOPUP', callback_data='TOPUP')
            ], [
                InlineKeyboardButton(text='CEK SALDO', callback_data='saldo'),
            ]
        ])
        sent = self.sender.sendMessage(
            'Selamat datang di menu utama, silahkan pilih produk yang anda cari.',
            reply_markup=keyboard)
        self._editor = telepot.helper.Editor(self.bot, sent)
        self._edit_mgs_ident = telepot.message_identifier(sent)
        self._level = 1
        self._code = None
        self._keyboard = [keyboard]
예제 #17
0
 def _propose(self):
     self._count += 1
     sent = self.sender.sendMessage(
         '%d. یکی از موضوعات زیر را انتخاب کنید' % self._count,
         reply_markup=self.keyboard)
     self._editor = telepot.helper.Editor(self.bot, sent)
     self._edit_msg_ident = message_identifier(sent)
예제 #18
0
파일: words.py 프로젝트: denolia/learnwords
def show_translation_to_repeat(bot, chat_id, query_id, query_data, username):
    word_id = query_data.replace('show_back_side_repeat_', '')
    log.debug("show translation to repeat word {}".format(word_id))

    word_info = fetch_word_info(bot, chat_id, username, word_id)

    if word_info:
        global message_with_inline_keyboard

        if message_with_inline_keyboard:
            log.debug("message: {}".format(message_with_inline_keyboard))

            msg_idf = telepot.message_identifier(message_with_inline_keyboard)
            keyboard = InlineKeyboardMarkup(inline_keyboard=[[
                InlineKeyboardButton(text="Don't remember",
                                     callback_data='not_repeated_{}'.format(
                                         word_info[0])),
                InlineKeyboardButton(text='Remember',
                                     callback_data='repeated_{}'.format(
                                         word_info[0]))
            ]])
            word = word_info[1] if word_info[1] is not None else ""
            translation = word_info[2] if word_info[2] is not None else ""
            pronunciation = word_info[3] if word_info[3] is not None else ""
            bot.editMessageText(msg_idf,
                                '{}\n{}\n{}'.format(word, translation,
                                                    pronunciation),
                                reply_markup=keyboard)
        else:
            bot.answerCallbackQuery(query_id,
                                    text='No previous message to edit')
예제 #19
0
 async def _propose(self):
     self._count += 1
     sent = await self.sender.sendMessage('%d. Would you marry me?' %
                                          self._count,
                                          reply_markup=self.keyboard)
     self._editor = telepot.aio.helper.Editor(self.bot, sent)
     self._edit_msg_ident = message_identifier(sent)
예제 #20
0
    def send_not_answer_reminder(self, msg):
        if not hasattr(self, 'last_reminder'):
            self.last_reminder = time.time() - 3600

        if time.time() - self.last_reminder < 120:
            print(
                'Not sending reminder, as previous reminder has been sent recently'
            )
            return
        from_member = Member(msg['from'])

        timer = 30
        text = f'Liebe*r <a href="tg://user?id={from_member.id}">{from_member}</a>, kleine Erinnerung: Bitte antworte im Hauptchat nur, wenn es für alle 1000+ Mitglieder relevant ist. ' \
               'Falls deine Antwort nur etwas wie <i>"Ich habe Interesse", "Danke", "Reserviert", etc</i>, ist,  lösche sie und ' \
               'sende besser eine private Nachricht an die betreffende Person, oder editiere deine ursprüngliche Nachricht. '\
               'Vielen Dank für dein Verständnis und habe noch einen schönen Tag 😊\n\n' \
               f'Diese Nachricht zerstört sich in {timer} Sekunden selbst 💣💥.'
        posted_msg = self.send_message(group_chat_id,
                                       text,
                                       parse_mode='html',
                                       disable_notification=True,
                                       reply_to_message_id=msg['message_id'])
        msg_identifier = telepot.message_identifier(posted_msg)
        Thread(target=destroy_message,
               kwargs={
                   'bot': bot,
                   'delay': timer,
                   'msg_identifier': msg_identifier
               }).start()
        self.last_reminder = time.time()
        self.send_message(
            admin_chat_id,
            f'No-Reply-Reminder sent to <a href="tg://user?id={from_member.id}">{from_member}</a>, destroy in 30 seconds',
            parse_mode='html',
            disable_notification=True)
예제 #21
0
파일: sender.py 프로젝트: NeXidan/tequ
    async def send_current_page(self):
        quest_state = self.user_state.get_quest_state()

        current_page = quest_state.get_current_page()
        if current_page is None:
            return await self.on_unknown()

        if not current_page.is_synced():
            current_page = current_page.read()

        current_page_message = quest_state.get_current_page_message()
        if current_page_message is not None:
            try:
                await self.bot.editMessageReplyMarkup(current_page_message,
                                                      reply_markup='')
            except TelegramError as error:
                pass

        actions = current_page.get_actions()
        if not len(actions):
            self.user_state.quest_state = None

        msg = await self.sender.sendMessage(
            current_page.get_text(),
            reply_markup={
                'inline_keyboard': [[{
                    'text':
                    action['text'] if 'text' in action else '',
                    'callback_data':
                    'action' + CALLBACK_QUERY_SEPARTOR + action['to']
                }] for action in actions]
            })

        quest_state.current_page_message = message_identifier(msg)
예제 #22
0
    def send_confirm_remove(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        msg_id = telepot.message_identifier(msg)
        to_delete_id = msg['text'][8:]

        res = self.getChatMember(group_chat_id, to_delete_id)
        if res['status'] != 'member':
            delete_member = Member(res['user'])
            self.send_message(
                admin_chat_id,
                f'can\'t remove {delete_member}, is not in chat user list, status is {res["status"]}'
            )
            return

        if not to_delete_id.isdigit():
            self.send_message(
                admin_chat_id,
                f'can\'t remove {to_delete_id}, wrong format of id')
            return
        keyboard = keyboard = [[
            KeyboardButton(text=f"/confirm_remove_{to_delete_id}"),
            KeyboardButton(text="/no")
        ]]
        self.send_message(admin_chat_id,
                          f'Do you really want to delete {to_delete_id}?',
                          reply_markup=ReplyKeyboardMarkup(
                              keyboard=keyboard, one_time_keyboard=True))
        self.deleteMessage(msg_id)  # remove the request message
예제 #23
0
파일: bot.py 프로젝트: yahya09/liga-badr
def on_callback_query(msg):
    query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
    print('Callback Query:', query_id, from_id, query_data)
    msg_id = telepot.message_identifier(msg['message'])
    bot.editMessageReplyMarkup(msg_id)
    bot.answerCallbackQuery(query_id, text='Sip, oke!')
    reply = "Maaf, ada kesalahan :("
    if 'history' in query_data:
        pid = int(query_data.split('-')[1])
        name, teams = herokudb.getTeamHistory(pid)
        reply = "Team history for {}:\n".format(name.upper())
        for key, team in enumerate(teams):
            reply += "{}. {} ({})\n".format(key+1, team[3].lower().title(), team[4][0].upper())
        if len(teams) == 0:
            reply += "(Belum ada)"
    elif 'match' in query_data:
        pid = int(query_data.split('-')[1])
        name, results = herokudb.getMatchHistory(pid)
        reply = "Match history for {}:\n".format(name.upper())
        for record in results:
            if record[7] == 'complete':
                reply += "vs. {}: {}-{}\n".format(record[4], record[2], record[5])
            else:
                reply += "vs. {}: \n".format(record[4])
        if len(results) == 0:
            reply += "(Belum ada)"

    #send result to existing message
    bot.editMessageText(msg_id, reply)
예제 #24
0
파일: words.py 프로젝트: denolia/learnwords
def show_next_word_to_repeat(bot, chat_id, query_id, date, username):
    log.debug("showing next word to repeat")

    word_to_repeat = None
    try:
        word_to_repeat = get_one_word_to_repeat(date, username)
        log.debug("word to repeat: {}".format(word_to_repeat))

    except Exception as e:
        bot.sendMessage(chat_id, 'Cannot fetch a word: {}'.format(e))
        log.error("Cannot fetch a word", exc_info=True)

    global message_with_inline_keyboard
    if message_with_inline_keyboard:
        log.debug("message: {}".format(message_with_inline_keyboard))

        msg_idf = telepot.message_identifier(message_with_inline_keyboard)
        if word_to_repeat is not None:
            keyboard = InlineKeyboardMarkup(inline_keyboard=[[
                InlineKeyboardButton(text='Show back side',
                                     callback_data='show_back_side_repeat_{}'.
                                     format(word_to_repeat[0]))
            ]])
            bot.editMessageText(msg_idf,
                                '{}'.format(word_to_repeat[1]),
                                reply_markup=keyboard)
        else:
            stop_lesson(bot, chat_id)
    else:
        bot.answerCallbackQuery(query_id, text='No previous message to edit')
예제 #25
0
 def remove_user(self, msg):
     content_type, chat_type, chat_id = telepot.glance(msg)
     msg_id = telepot.message_identifier(msg)
     from_member = Member(msg['from'])
     to_delete_id = int(msg['text'][16:])
     try:
         res = banChatMember(bot,
                             group_chat_id,
                             to_delete_id,
                             revoke_messages=True,
                             until_date=0)
         assert res == True, 'banChatMember did not return true'
         time.sleep(0.5)
         res = self.getChatMember(group_chat_id, to_delete_id)
         deleted_member = Member(res['user'])
         print(deleted_member)
         assert res[
             'status'] == 'kicked', f'User was not successfully removed: {res}'
         self.send_message(admin_chat_id, f'removed user <a href="tg://user?id={to_delete_id}">{deleted_member}</a> '\
                       f'(requested by {from_member}) ',  parse_mode = 'html')
     except Exception as e:
         print(e, repr(e))
         self.send_message(admin_chat_id, f'cannot remove user <a href="tg://user?id={to_delete_id}">{to_delete_id}</a> '\
                       f'(requested by {from_member}), error message: {e}',  parse_mode = 'html')
     self.deleteMessage(msg_id)  # remove the request message
예제 #26
0
    def list_modules():
        keyboard = InlineKeyboardMarkup(
            inline_keyboard=[[
                InlineKeyboardButton(text=mod_name,
                                     callback_data="modules:run:" + mod_name)
                for mod_name in config['REGISTRY']
            ],
                             [
                                 InlineKeyboardButton(
                                     text="<- Back",
                                     callback_data="menu:back:settings"),
                             ]])

        global inline_id
        if inline_id:
            msg_idf = telepot.message_identifier(inline_id)
            # bot.editMessageReplyMarkup(msg_idf, reply_markup=keyboard)
            bot.editMessageText(msg_idf,
                                text='Modules :',
                                reply_markup=keyboard)
        else:
            inline_id = bot.sendMessage(from_id,
                                        'Modules :',
                                        reply_markup=keyboard)

        bot.answerCallbackQuery(query_id, 'Choosing detection module')
예제 #27
0
def on_callback_query(msg):
    global usernamedata
    global chatId
    global isButtonTime
    global button
    global HinterList
    global can_hint
    global isEnd
    global message_with_inline_keyboard
    query_id, from_id, query_data = telepot.glance(msg,
                                                   flavor='callback_query')
    msg_idf = telepot.message_identifier(message_with_inline_keyboard)
    print("idf", msg_idf)
    print('Callback Query:', query_id, from_id, query_data)
    if (query_data in usernamedata):
        vote(("@" + str(msg['from']['username'])), query_data)
        bot.answerCallbackQuery(query_id, text='投票囉')
    elif (query_data == "結束投票"):

        bot.answerCallbackQuery(query_id, text='結束投票囉')
        if message_with_inline_keyboard:
            bot.editMessageText(msg_idf, printVote())
            dealVote()
            if not isEnd:
                HinterList = usernamedata
                index = 0
                can_hint = True
                bot.sendMessage(chatId, '現在進入到提示環節~')
                bot.sendMessage(
                    chatId, '首先輪到' + str(HinterList[index]) +
                    '提供提示\n提示的格式:「/hint [提示內容]」')

        else:
            bot.answerCallbackQuery(query_id,
                                    text='No previous message to edit')
예제 #28
0
    def _show_next_question(self,msg):

        chat_id=telepot.glance(msg, flavor='callback_query')

        a = TeleUser.objects.get(user_id=msg['from']['id'])
        words=Word.objects.filter(teleuser=a).filter(Q(next_review_time__lte=datetime.now())|Q(next_review_time=None)).order_by('-next_review_time').last()
        if words:
            choice=Word.objects.filter(teleuser=a).exclude(pk=words.pk).order_by('?').all()[:3]
            list=[]
            for i in choice:
                list.append(i)
            answer=words.pk
            list.append(words)
            random.shuffle(list)
            question = '{word} ❓ \n\n' \
                       '1️⃣- {one} \n\n' \
                       '2️⃣- {two} \n\n' \
                       '3️⃣- {three} \n\n' \
                       '4️⃣- {four} \n\n'.format(word=words.word,one=list[0].meaning,two=list[1].meaning,three=list[2].meaning,four=list[3].meaning)

            key3 = InlineKeyboardMarkup(inline_keyboard=[[
                InlineKeyboardButton(text=str(1), callback_data=str(list[0].pk)),InlineKeyboardButton(text=str(2), callback_data=str(list[1].pk)),
                InlineKeyboardButton(text=str(3), callback_data=str(list[3].pk)),InlineKeyboardButton(text=str(4), callback_data=str(list[2].pk))
                ]])

            new=bot.editMessageText(msg_identifier=self._message_ind,text=question,reply_markup=key3)

            self._message_ind=telepot.message_identifier(new)

        else:
            self.sender.sendMessage('هیچ لغتی برای مرور موجود نیست')

        return answer
예제 #29
0
    async def on_chat_message(self, msg):

        if "sticker" in msg:
            await self.sender.sendSticker(msg["sticker"]["file_id"])
            return

        content_type, chat_type, chat_id = telepot.glance(msg)
        if msg["text"] == "/start":
            await self.sender.sendMessage(
                "Привет! Пришли мне URL на новость на lenta.ru.")
            return
        if msg["text"] == "/list":
            await self.send_list()
            return

        parsed_url = urlparse(msg["text"])
        if not parsed_url.scheme:
            await self.sender.sendMessage(
                "Что-то не так с твоим адресом, попробуй еще")
            return
        elif parsed_url.netloc != "lenta.ru":
            await self.sender.sendMessage("Не похоже, что это URL на lenta.ru")
            return

        async with self._session.get(parsed_url.geturl()) as resp:
            soup = BS(await resp.text(), "lxml")
            sent = await self.sender.sendMessage(soup.find(
                "div", {
                    "class": "b-text"
                }).get_text(),
                                                 reply_markup=self.keyboard)
            self._editor = telepot.aio.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)
예제 #30
0
def adminMode(msg, args):
    """/adminmode password : enters or leaves admin mode."""
    chat_id = msg['chat']['id']
    if len(args) == 0:
        bot.sendMessage(chat_id, "No password entered.")
        return
    password = args[0]
    if chat_id in admin_authorized.keys():
        print(password)
        print(hashlib.sha512(password.encode()).hexdigest())
        if hashlib.sha512(
                password.encode()).hexdigest() == admin_authorized[chat_id]:
            if chat_id in admin_id:
                admin_id.remove(chat_id)
                print("Admin " + str(chat_id) + " logged out.")
                bot.sendMessage(chat_id, "Admin mode off.")
            else:
                admin_id.append(chat_id)
                print("Admin " + str(chat_id) + " logged in.")
                bot.sendMessage(chat_id, "Admin mode on.")
        else:
            print("Wrong password entered by " + str(chat_id))
            bot.sendMessage(chat_id, "Wrong password entered.")
    else:
        print("Unknown chat_id entered by " + str(chat_id))
        bot.sendMessage(chat_id,
                        "Wrong user. Not allowed to enter admin mode.")
    bot.deleteMessage(telepot.message_identifier(msg))
    return
예제 #31
0
파일: keyboard.py 프로젝트: xurxodiz/rpgbot
    def send(self, msg, target=None, disablepreview=True, options={}, allowedit=False):
        if (msg == None or len(msg) == 0 or len(msg.split()) == 0) and len(options) == 0:
            msg = '(no message)'

        keyboard = None
        if len(options) > 0:
            buttons = []
            for key, value in options.items():
                if isinstance(value, dict):
                    if 'url' in value:
                        buttons.append([InlineKeyboardButton(text=key, url=value['url'])])
                    else:
                        sublist = []
                        for key, subvalue in value.items():
                            if isinstance(subvalue, dict) and 'url' in subvalue:
                                sublist.append(InlineKeyboardButton(text=key, url=subvalue['url']))
                            else:
                                sublist.append(InlineKeyboardButton(text=key, callback_data=subvalue))
                        buttons.append(sublist)
                else:
                    buttons.append([InlineKeyboardButton(text=key, callback_data=value)])
            keyboard = InlineKeyboardMarkup(inline_keyboard=buttons)
        
        #log('sending to chat id {}'.format(target))
        if target is None:
            if self.message is not None:
                self.bot.deleteMessage(self.message)
                self.message = None
            sent = self.bot.sendMessage(self.chat_id, msg, disable_web_page_preview=disablepreview, reply_markup=keyboard)
            if allowedit:
                self.message = telepot.message_identifier(sent)
            else:
                self.message = None
        else:
            self.bot.sendMessage(target, msg, disable_web_page_preview=disablepreview, reply_markup=keyboard)
예제 #32
0
    def process_callback(self, msg):

        message_idf = telepot.message_identifier(msg['message'])

        data = {
            'user_id': self.user_id,
            'cb_data': u.get_callback_data(msg),
            'message_idf': message_idf
        }

        reply = self.get_reply(data)
        self.send_reply(reply, message_idf)
예제 #33
0
파일: bot.py 프로젝트: FezZHD/jigglypuff
    def location(self, msg, step = 5):
        reply = telepot.message_identifier(self.sender.sendMessage(consts.BOT['LOCATION']['REPLY'] % (0, 0), parse_mode = 'Markdown'))

        def handler(pokemons = None, image = None, current_steps = 0, total_steps = 0):
            self.bot.editMessageText(reply, consts.BOT['LOCATION']['REPLY'] % (current_steps, total_steps), parse_mode = 'Markdown')
            if image is not None:
                path = utils.path(__file__, '../tmp/' + str(self.chat_id) + '.png')
                image.save(path, 'PNG')
                with open(path, 'rb') as imageFile:
                    self.sender.sendPhoto(imageFile)

        Map(location = msg['location'], callback = handler, step = step)
예제 #34
0
    def _init_ballot(self):
        keyboard = InlineKeyboardMarkup(inline_keyboard=[[
                       InlineKeyboardButton(text='Yes', callback_data='yes'),
                       InlineKeyboardButton(text='Nah!!!!', callback_data='no'),
                   ]])
        sent = self.sender.sendMessage("Let's Vote ...", reply_markup=keyboard)

        self._ballot_box = {}
        self._keyboard_msg_ident = telepot.message_identifier(sent)
        self._editor = telepot.helper.Editor(self.bot, self._keyboard_msg_ident)

        # Generate an expiry event 30 seconds later
        self._expired_event = self.scheduler.event_later(30, ('_vote_expired', {'seconds': 30}))
예제 #35
0
파일: bot.py 프로젝트: FezZHD/jigglypuff
    def command_keyboard(self, msg):
        if not hasattr(self, 'keyboard'):
            self.keyboard = telepot.message_identifier(self.sender.sendMessage(
                'Use this keyboard to interact with *Jigglypuff*',
                parse_mode = 'Markdown',
                reply_markup = consts.BOT['KEYBOARD']['SHOW']
            ))
            return

        self.sender.sendMessage(
            '*Jigglypuff* will hide keyboard',
            parse_mode = 'Markdown',
            reply_markup = consts.BOT['KEYBOARD']['HIDE']
        )
        del self.keyboard
예제 #36
0
    async def _init_ballot(self):
        keyboard = InlineKeyboardMarkup(inline_keyboard=[[
                       InlineKeyboardButton(text='Yes', callback_data='yes'),
                       InlineKeyboardButton(text='Nah!!!!', callback_data='no'),
                   ]])
        sent = await self.sender.sendMessage("Let's Vote ...", reply_markup=keyboard)

        self._member_count = await self.administrator.getChatMembersCount() - 1  # exclude myself, the bot

        self._ballot_box = {}
        self._keyboard_msg_ident = message_identifier(sent)
        self._editor = telepot.aio.helper.Editor(self.bot, self._keyboard_msg_ident)

        # Generate an expiry event 30 seconds later
        self._expired_event = self.scheduler.event_later(30, ('_vote_expired', {'seconds': 30}))
예제 #37
0
def on_callback_query(msg):
    query_id, from_id, data = telepot.glance(msg, flavor='callback_query')
    print 'Callback query:', query_id, from_id, data

    if data == 'notification':
        bot.answerCallbackQuery(query_id, text='Notification at top of screen')
    elif data == 'alert':
        bot.answerCallbackQuery(query_id, text='Alert!', show_alert=True)
    elif data == 'edit':
        global message_with_inline_keyboard

        if message_with_inline_keyboard:
            msg_idf = telepot.message_identifier(message_with_inline_keyboard)
            bot.editMessageText(msg_idf, 'NEW MESSAGE HERE!!!!!')
        else:
            bot.answerCallbackQuery(query_id, text='No previous message to edit')
예제 #38
0
  def on_callback_query(self, msg): 
    query_id, from_id, data = telepot.glance(msg, flavor='callback_query')

    if not self.edtTorrents:
      self.bot.answerCallbackQuery(query_id, 
        text='Overdue list, please search again')
      return 

    id = telepot.message_identifier(self.edtTorrents) 
    torrent = self.torrents[int(data)]

    if self.mode == 'search':
      self.bot.editMessageText(id, 'Adding,  %s' % 
        self.torrents[int(data)]['title'], reply_markup=None)
      self.addTorrent(torrent['magnet'])

    elif self.mode == 'delete': 
      self.bot.editMessageText(id, 'Deleting, %s' % 
       self.torrents[int(data)]['title'], reply_markup=None)
      self.deleteTorrent(torrent['id'])
예제 #39
0
def send_everything_on_contact(msg):
    content_type, chat_type, chat_id, msg_date, msg_id = telepot.glance(msg, long=True)

    if chat_id != USER_ID:
        print 'Unauthorized user:'******'from']['id']
        exit(1)

    print 'Received message from ID: %d' % chat_id
    print 'Start sending various messages ...'

    ##### forwardMessage

    r = bot.forwardMessage(chat_id, chat_id, msg_id)
    examine(r, telepot.namedtuple.Message)

    ##### sendMessage

    r = bot.sendMessage(chat_id, 'Hello, I am going to send you a lot of things.', reply_to_message_id=msg_id)
    examine(r, telepot.namedtuple.Message)
    time.sleep(0.5)  # slow it down for inspecting messages

    r = bot.sendMessage(chat_id, u'中文')
    examine(r, telepot.namedtuple.Message)
    time.sleep(0.5)

    r = bot.sendMessage(chat_id, '*bold text*\n_italic text_\n[link](http://www.google.com)', parse_mode='Markdown')
    examine(r, telepot.namedtuple.Message)
    time.sleep(0.5)

    bot.sendMessage(chat_id, 'http://www.yahoo.com\nwith web page preview')
    time.sleep(0.5)

    bot.sendMessage(chat_id, 'http://www.yahoo.com\nno web page preview', disable_web_page_preview=True)
    time.sleep(0.5)

    show_keyboard = {'keyboard': [['Yes', 'No'], ['Maybe', 'Maybe not']]}
    remove_keyboard = {'remove_keyboard': True}
    force_reply = {'force_reply': True}

    nt_show_keyboard = telepot.namedtuple.ReplyKeyboardMarkup(**show_keyboard)
    nt_remove_keyboard = telepot.namedtuple.ReplyKeyboardRemove(**remove_keyboard)
    nt_force_reply = telepot.namedtuple.ForceReply(**force_reply)

    bot.sendMessage(chat_id, 'Here is a custom keyboard', reply_markup=show_keyboard)
    time.sleep(0.5)

    bot.sendMessage(chat_id, 'Hiding it now.', reply_markup=nt_remove_keyboard)
    time.sleep(0.5)

    bot.sendMessage(chat_id, 'Force reply', reply_markup=nt_force_reply)
    time.sleep(0.5)

    ##### sendPhoto

    bot.sendChatAction(chat_id, 'upload_photo')
    r = bot.sendPhoto(chat_id, open('lighthouse.jpg', 'rb'))
    examine(r, telepot.namedtuple.Message)

    file_id = r['photo'][0]['file_id']

    bot.sendPhoto(chat_id, file_id, caption='Show original message and keyboard', reply_to_message_id=msg_id, reply_markup=nt_show_keyboard)
    time.sleep(0.5)

    bot.sendPhoto(chat_id, file_id, caption='_Hide keyboard_', parse_mode='Markdown', reply_markup=remove_keyboard)
    time.sleep(0.5)

    furl = urllib2.urlopen('http://i.imgur.com/35HSRQ6.png')
    bot.sendPhoto(chat_id, ('abc.jpg', furl))
    time.sleep(0.5)

    bot.sendPhoto(chat_id, (u'中文照片.jpg', open('lighthouse.jpg', 'rb')), caption=u'中文照片')
    time.sleep(0.5)

    ##### getFile

    f = bot.getFile(file_id)
    examine(f, telepot.namedtuple.File)

    ##### download_file, smaller than one chunk (65K)

    try:
        print 'Downloading file to non-existent directory ...'
        bot.download_file(file_id, 'non-existent-dir/file')
    except:
        print 'Error: as expected'

    print 'Downloading file to down.1 ...'
    bot.download_file(file_id, 'down.1')

    print 'Open down.2 and download to it ...'
    with open('down.2', 'wb') as down:
        bot.download_file(file_id, down)

    ##### sendAudio
    # Need one of `performer` or `title' for server to regard it as audio. Otherwise, server treats it as voice.

    bot.sendChatAction(chat_id, 'upload_audio')
    r = bot.sendAudio(chat_id, open('dgdg.mp3', 'rb'), title='Ringtone')
    examine(r, telepot.namedtuple.Message)
    time.sleep(0.5)

    file_id = r['audio']['file_id']

    bot.sendAudio(chat_id, file_id, duration=6, performer='Ding Dong', title='Ringtone', reply_to_message_id=msg_id, reply_markup=show_keyboard)
    time.sleep(0.5)

    bot.sendAudio(chat_id, file_id, performer='Ding Dong', reply_markup=nt_remove_keyboard)
    time.sleep(0.5)

    bot.sendAudio(chat_id, (u'中文歌.mp3', open('dgdg.mp3', 'rb')), title=u'中文歌')
    time.sleep(0.5)

    ##### sendDocument

    bot.sendChatAction(chat_id, 'upload_document')
    r = bot.sendDocument(chat_id, open('document.txt', 'rb'))
    examine(r, telepot.namedtuple.Message)
    time.sleep(0.5)

    file_id = r['document']['file_id']

    bot.sendDocument(chat_id, file_id, reply_to_message_id=msg_id, reply_markup=nt_show_keyboard)
    time.sleep(0.5)

    bot.sendDocument(chat_id, file_id, reply_markup=remove_keyboard)
    time.sleep(0.5)

    bot.sendDocument(chat_id, (u'中文文件.txt', open('document.txt', 'rb')))
    time.sleep(0.5)

    ##### sendSticker

    r = bot.sendSticker(chat_id, open('gandhi.png', 'rb'))
    examine(r, telepot.namedtuple.Message)
    time.sleep(0.5)

    file_id = r['sticker']['file_id']

    bot.sendSticker(chat_id, file_id, reply_to_message_id=msg_id, reply_markup=show_keyboard)
    time.sleep(0.5)

    bot.sendSticker(chat_id, file_id, reply_markup=nt_remove_keyboard)
    time.sleep(0.5)

    ##### sendVideo

    bot.sendChatAction(chat_id, 'upload_video')
    r = bot.sendVideo(chat_id, open('hktraffic.mp4', 'rb'))
    examine(r, telepot.namedtuple.Message)
    time.sleep(0.5)

    try:
        file_id = r['video']['file_id']

        bot.sendVideo(chat_id, file_id, duration=5, caption='Hong Kong traffic', reply_to_message_id=msg_id, reply_markup=nt_show_keyboard)
        time.sleep(0.5)
        bot.sendVideo(chat_id, file_id, reply_markup=remove_keyboard)
        time.sleep(0.5)

    except KeyError:
        # For some reason, Telegram servers may return a document.
        print '****** sendVideo returns a DOCUMENT !!!!!'

        file_id = r['document']['file_id']

        bot.sendDocument(chat_id, file_id, reply_to_message_id=msg_id, reply_markup=nt_show_keyboard)
        time.sleep(0.5)
        bot.sendDocument(chat_id, file_id, reply_markup=remove_keyboard)
        time.sleep(0.5)

    ##### download_file, multiple chunks

    print 'Downloading file to down.3 ...'
    bot.download_file(file_id, 'down.3')

    ##### sendVoice

    r = bot.sendVoice(chat_id, open('example.ogg', 'rb'))
    examine(r, telepot.namedtuple.Message)
    time.sleep(0.5)

    file_id = r['voice']['file_id']

    bot.sendVoice(chat_id, file_id, duration=6, reply_to_message_id=msg_id, reply_markup=show_keyboard)
    time.sleep(0.5)

    bot.sendVoice(chat_id, file_id, reply_markup=nt_remove_keyboard)
    time.sleep(0.5)

    ##### sendVideoNote

    bot.sendVideoNote(chat_id, open('hktraffic.mp4', 'rb'), length=2)

    ##### sendMediaGroup

    with open('lighthouse.jpg', 'rb') as f1, open('gandhi.png', 'rb') as f2, open('bookshelf.jpg', 'rb') as f3, open('saturn.jpg', 'rb') as f4:
        ms = [
            telepot.namedtuple.InputMediaPhoto(media=f1),
            telepot.namedtuple.InputMediaPhoto(media=('media2', f2)),
            telepot.namedtuple.InputMediaPhoto(media='https://telegram.org/file/811140935/175c/FSf2aidnuaY.21715.gif/31dc2dbb6902dcef78'),
            {'type': 'photo', 'media': ('media3', ('books.jpg', f3))},
            {'type': 'photo', 'media': f4},
        ]
        bot.sendMediaGroup(chat_id, ms)

    ##### sendLocation

    bot.sendChatAction(chat_id, 'find_location')
    r = bot.sendLocation(chat_id, 22.33, 114.18)  # Hong Kong
    examine(r, telepot.namedtuple.Message)
    time.sleep(0.5)

    bot.sendLocation(chat_id, 49.25, -123.1, reply_to_message_id=msg_id, reply_markup=nt_show_keyboard)  # Vancouver
    time.sleep(0.5)

    bot.sendLocation(chat_id, -37.82, 144.97, reply_markup=remove_keyboard)  # Melbourne
    time.sleep(0.5)

    r = bot.sendLocation(chat_id, -37.82, 144.97, live_period=60)  # Melbourne
    time.sleep(3)

    mif = telepot.message_identifier(r)
    bot.editMessageLiveLocation(mif, -37.819, 144.97)
    time.sleep(1)

    bot.editMessageLiveLocation(mif, -37.818, 144.97)
    time.sleep(1)

    bot.stopMessageLiveLocation(mif)

    ##### sendGame

    bot.sendGame(chat_id, 'sunchaser')
    time.sleep(0.5)

    game_keyboard = telepot.namedtuple.InlineKeyboardMarkup(inline_keyboard=[[
                        telepot.namedtuple.InlineKeyboardButton(text='Play now', callback_game=True),
                        telepot.namedtuple.InlineKeyboardButton(text='How to play?', url='https://mygame.com/howto'),
                    ]])
    bot.sendGame(chat_id, 'sunchaser', reply_markup=game_keyboard)
    time.sleep(0.5)

    ##### Done sending messages

    bot.sendMessage(chat_id, 'I am done.')
예제 #40
0
 def editLastMessage(self, msg):
   if self.edtMsg:
     id = telepot.message_identifier(self.edtMsg)
     self.bot.editMessageText(id, msg, reply_markup=None)
     self.edtMsg = None
예제 #41
0
 def _propose(self):
     self._count += 1
     sent = self.sender.sendMessage('%d. Would you marry me?' % self._count, reply_markup=self.keyboard)
     self._editor = telepot.helper.Editor(self.bot, sent)
     self._edit_msg_ident = telepot.message_identifier(sent)
예제 #42
0
    def on_message(self, msg):
        # super(UserHandlerSubclass, self).on_message(msg)
        if self.new_user:
            self.new_user_notification(msg)
        print_terminal(msg)
        global message_with_inline_keyboard
        flavor = telepot.flavor(msg)
        cmd = Commands
        st = States
        if flavor == 'chat':
            content_type, chat_type, chat_id = telepot.glance(msg)
            print_terminal(telepot.glance(msg))
            print_terminal('-' * 20)

            # Do your stuff according to `content_type`
            if content_type == 'text':
                message = (msg['text']).encode('utf-8')
                if message == cmd.start:
                    f_name = (msg['from']['first_name'])  # .decode('utf-8')
                    has_profile = db_ops.register_user(chat_id)
                    self.fsm.reset()
                    if has_profile:
                        markup = get_main_menu_keyboard_markup()
                        bot.sendMessage(chat_id, 'خوش آمدی ' + f_name.encode('utf-8'), reply_markup=markup)
                    else:
                        bot.sendMessage(chat_id, survey1.fill_info)
                        self.fsm.profile()
                        # ops.set_state(chat_id, st.profile)
                        ask_profile(chat_id, self.fsm.get_state_as_list()[1])

                elif message == cmd.test1:
                    self.fsm.test1()
                    db_ops.clear_pre_session(chat_id)
                    ask(chat_id, 1)

                elif message == cmd.test2:
                    # self.fsm.test2()
                    # ask2(chat_id, 1)
                    bot.sendMessage(chat_id, "به زودی...")

                elif message == cmd.profile:
                    self.fsm.profile()
                    ask_profile(chat_id, self.fsm.get_state_as_list()[1])

                elif message == cmd.account:
                    # self.fsm.account()
                    markup = ReplyKeyboardMarkup(keyboard=[[cmd.profile, cmd.membership], [cmd.to_main_menu]])
                    bot.sendMessage(chat_id, Misc.my_account, reply_markup=markup)

                elif message == cmd.membership:
                    bot.sendMessage(chat_id, Misc.free_membership)
                    # membership, transid = db_ops.get_membership_status(self.user_id)
                    # print membership, transid
                    # if membership == 'gold':
                    #     bot.sendMessage(self.user_id, Misc.golden_user_msg)
                    # elif transid is not None:
                    #     code = pal.verify_transaction(transid)
                    #     if code.isdigit() and int(code) == 1:
                    #         db_ops.set_membership(self.user_id, 'gold')
                    #         bot.sendMessage(self.user_id, Misc.golden_user_new)
                    #     else:
                    #         pay_link = pal.get_pay_link(transid)
                    #         markup = InlineKeyboardMarkup(inline_keyboard=[
                    #             [InlineKeyboardButton(text='پرداخت', url=pay_link, callback_data='payment')]])
                    #         bot.sendMessage(chat_id, Misc.pay_msg, reply_markup=markup)
                    # else:
                    #     code, transid = pal.create_transaction()
                    #     if code == 1:  # successful
                    #         db_ops.save_transaction(self.user_id, transid)
                    #         pay_link = pal.get_pay_link(transid)
                    #         print pay_link
                    #         markup = InlineKeyboardMarkup(inline_keyboard=[
                    #             [InlineKeyboardButton(text='پرداخت', url=pay_link, callback_data='payment')]])
                    #         bot.sendMessage(chat_id, Misc.pay_msg, reply_markup=markup)
                    #     else:  # timeout and other reasons
                    #         bot.sendMessage(self.user_id, Misc.timeout_msg)

                elif message == cmd.share_contact:
                    markup = ReplyKeyboardMarkup(keyboard=[
                        [dict(text=Misc.contact_no, request_contact=True),
                         KeyboardButton(text=Misc.location_zone, request_location=True)],
                        [cmd.to_main_menu]],
                        one_time_keyboard=True)
                    bot.sendMessage(
                        chat_id, Misc.share_contact_msg, reply_markup=markup)
                    self.fsm.main()

                elif message == cmd.help:
                    markup = get_main_menu_keyboard_markup()
                    bot.sendMessage(chat_id, survey1.help_message, reply_markup=markup)

                # elif message == cmd.to_main_menu:
                #     markup = get_main_menu_keyboard_markup()
                #     bot.sendMessage(chat_id, Label.main_menu, reply_markup=markup)

                # For Debugging
                ##########
                elif message.lower() == cmd.box:
                    gift = u'\U0001f381'
                    key_arr = [InlineKeyboardButton(text=gift, callback_data=str(i)) for i in range(5)]
                    markup = InlineKeyboardMarkup(inline_keyboard=[key_arr])
                    message_with_inline_keyboard = bot.sendMessage(chat_id, 'select a box', reply_markup=markup)
                elif message.lower() == cmd.print_db:
                    bot.sendMessage(chat_id, db_ops.print_table_contents('users'))
                    db_ops.set_state(chat_id, st.main_menu)
                elif message.lower() == cmd.feedback:
                    print_feedback(chat_id)

                elif message.lower() == cmd.clear:
                    db_ops.delete_user(chat_id)
                ##########

                else:
                    ''' msg['text'] is not a command '''
                    user_input = msg['text']
                    # ---- Test1 -----
                    if self.fsm.get_state_prefix() == States.test1:
                        if utils.validate_user_input_for_test1(user_input):
                            q_num = int(self.fsm.get_q_num())
                            ans = utils.parse_answer_value_for_test1(user_input)
                            db_ops.save_answer(chat_id, q_num, ans)
                            if self.fsm.get_q_num() < 10:
                                if self.thread.isAlive():
                                    # ask again
                                    self.thread.cancel()
                                    bot.sendMessage(self.user_id, survey1.duplicate_answer_warning1)
                                    ask(chat_id, q_num)
                                else:
                                    # wait before ask
                                    bot.sendChatAction(chat_id, 'typing')
                                    self.thread = threading.Timer(1.4, self.wait_before_ask)
                                    self.thread.start()
                            else:  # Test1 completed
                                self.fsm.result1()
                                test1_completed(chat_id)
                        else:  # invalid user input in test 1
                            bot.sendMessage(chat_id, survey1.invalid_input, reply_markup=ReplyKeyboardHide())
                    # ----- Test2 -----
                    elif self.fsm.get_state_prefix() == States.test2:
                        part = int(self.fsm.get_state_as_list()[1])
                        if utils.validate_user_input_for_test2(user_input, part, self.fsm.t2_dream_category):
                            if part == 1:
                                self.fsm.t2_dream_category = utils.parse_answer_value_for_test2(user_input, 1)
                                self.fsm.next_part()
                                ask2(chat_id, 2, self.fsm.t2_dream_category)
                            elif part == 2:
                                self.fsm.t2_dream_subject = utils.parse_answer_value_for_test2(user_input, 2,
                                                                                               self.fsm.t2_dream_category)
                                # self.fsm.next_part()
                                # ask2(chat_id, 3, self.fsm.t2_dream_category, 0)
                                # skip part 3
                                test2_completed(chat_id, self.fsm.t2_dream_category, self.fsm.t2_dream_subject)
                                self.fsm.reset()
                            else:  # part == 3
                                q_num = self.fsm.get_q_num()
                                if q_num < 7:
                                    self.fsm.next_q()
                                    ask2(chat_id, part, self.fsm.t2_dream_category, q_num)
                                else:
                                    self.fsm.result2()
                                    test2_completed(chat_id, self.fsm.t2_dream_category, self.fsm.t2_dream_subject)
                                    self.fsm.reset()
                        else:  # invalid user input in test 2
                            bot.sendMessage(chat_id, survey1.invalid_input, reply_markup=ReplyKeyboardHide())

                    elif self.fsm.get_state_prefix() == 'Result2':
                        self.fsm.reset()
                        pass
                    # ----- Profile -----
                    elif self.fsm.get_state_prefix() == States.profile:
                        response = (msg['text']).encode('utf-8')
                        markup = get_main_menu_keyboard_markup()
                        if response == Commands.to_main_menu:
                            self.fsm.reset()
                            bot.sendMessage(self.user_id, Misc.back_to_main_menu_message, reply_markup=markup)
                        elif self.fsm.get_state_as_list()[1] == 'Gender':
                            if response in profile_gender_options.keys():
                                db_ops.save_profile(chat_id, 'gender', profile_gender_options[response])
                                self.fsm.next_q()
                                ask_profile(chat_id, self.fsm.get_state_as_list()[1])
                            else:
                                bot.sendMessage(self.user_id, survey1.invalid_input)
                        elif response in utils.age_range():  # sub_state equals 'Age'
                            for i, item in enumerate(utils.age_range()):
                                if response == item:
                                    db_ops.save_profile(chat_id, 'age', i)
                            self.fsm.reset()
                            bot.sendMessage(chat_id, survey1.info_complete, reply_markup=markup)
                        else:
                            bot.sendMessage(chat_id, survey1.invalid_input, reply_markup=ReplyKeyboardHide())
                    # ----- Main -----
                    elif self.fsm.get_state_prefix() == States.main_menu:
                        markup = get_main_menu_keyboard_markup()
                        bot.sendMessage(chat_id, 'منوی اصلی', reply_markup=markup)
                    # ----- Unknown State -----
                    else:
                        markup = get_main_menu_keyboard_markup()  # reply_markup=ReplyKeyboardHide()
                        bot.sendMessage(chat_id, Misc.unknown_state, reply_markup=markup)
                        self.fsm.reset()

            elif content_type == 'contact':
                if 'phone_number' in msg['contact']:
                    db_ops.save_phone_number(chat_id, msg['contact']['phone_number'])
                    markup = get_main_menu_keyboard_markup()
                    bot.sendMessage(chat_id, Label.main_menu, reply_markup=markup)

        elif flavor == 'callback_query':
            print "gotcha"
            query_id, from_id, data = telepot.glance(msg, flavor='callback_query')
            print_terminal('Callback query: {0} {1} {2}'.format(query_id, from_id, data))
            if not str(data).isdigit():
                markup = get_main_menu_keyboard_markup()
                bot.sendMessage(from_id, Misc.back_to_main_menu_message, reply_markup=markup)
                self.fsm.reset()
            else:
                index = int(data)
                if index in range(5):
                    # check to see if user is allowed to open the box[data]
                    res_array = db_ops.get_test1_result(from_id)
                    bot.sendChatAction(from_id, 'typing')
                    time.sleep(1)
                    bot.sendMessage(from_id, text=survey1.FEEDBACK[index][int(res_array[index])])
                    box_state = db_ops.get_box(from_id)
                    box_state = list('xxxxx') if box_state is None else list(box_state)
                    o_cnt1 = box_state.count('o')
                    box_state[index] = 'o'
                    o_cnt2 = box_state.count('o')
                    db_ops.save_box(from_id, box_state)
                    markup = get_gift_box_keyboard_markup(''.join([str(i) for i in box_state]), index)
                    bot.sendMessage(from_id, survey1.box_opened, reply_markup=markup)
                    # if message_with_inline_keyboard:
                    # msg_idf = telepot.message_identifier(message_with_inline_keyboard)
                    # bot.editMessageReplyMarkup(msg_idf, reply_markup=markup)
                    # message_with_inline_keyboard = bot.sendMessage(from_id, survey1.box_opened)
                    # else:
                    # bot.answerCallbackQuery(query_id, text='No previous message to edit')
                    if o_cnt2 > o_cnt1 and o_cnt2 == 5:
                        bot.sendMessage(from_id, survey1.bot_intro_msg)

                elif data == 'alert':
                    bot.answerCallbackQuery(query_id, text='Alert!', show_alert=True)
                elif data == 'edit':
                    if message_with_inline_keyboard:
                        msg_idf = telepot.message_identifier(message_with_inline_keyboard)
                        bot.editMessageText(msg_idf, 'NEW MESSAGE HERE!!!!!')
                    else:
                        bot.answerCallbackQuery(query_id, text='No previous message to edit')

        elif flavor == 'inline_query':
            pass

        elif flavor == 'chosen_inline_result':
            pass