def edit(bot, update):
    """
    Starts the progress to change a user data

    Args:
        bot (telegram.Bot) - The bot that is running
        update (telegram.Update) - Incoming Update
    """
    # Generates the Keyboard
    button_list = [
        # Keyboard button             Text to be displayed     data to be send on click
        #                                                      type to define the function
        #                                                      id the actual needed value
        telegram.InlineKeyboardButton('Vorname', callback_data=json.dumps({'type': 'reg', "id": '0'})),
        telegram.InlineKeyboardButton('Nachname', callback_data=json.dumps({'type': 'reg', "id": '1'})),
        telegram.InlineKeyboardButton('E-Mail', callback_data=json.dumps({'type': 'reg', "id": '2'})),
        telegram.InlineKeyboardButton('Passwort', callback_data=json.dumps({'type': 'reg', "id": '3'})),
        telegram.InlineKeyboardButton('Stadt', callback_data=json.dumps({'type': 'reg', "id": '4'})),
        telegram.InlineKeyboardButton('PLZ', callback_data=json.dumps({'type': 'reg', "id": '5'})),
        telegram.InlineKeyboardButton('Straße', callback_data=json.dumps({'type': 'reg', "id": '6'})),
        telegram.InlineKeyboardButton('Hausnummer', callback_data=json.dumps({'type': 'reg', "id": '7'})),
        telegram.InlineKeyboardButton('Handy Nummer', callback_data=json.dumps({'type': 'reg', "id": '8'})),
        telegram.InlineKeyboardButton('Delete', callback_data=json.dumps({"type": "reg", "id": 'del'}))
    ]

    # Generates a nice keyboard style and adds it to the reply markup
    reply_markup = telegram.InlineKeyboardMarkup(build_menu(button_list, n_cols=2))
    # Sends the keyboard
    bot.sendMessage(update.message.chat.id, "Was möchten sie ändern?", reply_markup=reply_markup)
Exemple #2
0
    def play_move5(self, bot, update, id):
        mc = self.games5[id][0].board.move_count

        if self.games5[id][0].board.get_turn() == self.games5[id][2]:
            self.get_player_move5(bot, update, id)
        else:
            if self.games5[id][0].board.move_count == 0:
                pl_mv = evaluation.firstmove(self.games5[id][0].board)
            elif self.games5[id][0].board.move_count == 1:
                pl_mv = evaluation.secondmove(self.games5[id][0].board)
            else:
                pl_mv = evaluation.nextMove(self.games5[id][0].board, 2, 3)
            self.games5[id][0].board.move(pl_mv)

        for i in range(self.board_size):
            for j in range(self.board_size):
                if self.games5[id][0].board.board[i][j] == gomokuboard.State.X:
                    self.games5[id][1][i][j] = telegram.InlineKeyboardButton(
                        "❌", callback_data=str(i * self.board_size + j))
                elif self.games5[id][0].board.board[i][
                        j] == gomokuboard.State.O:
                    self.games5[id][1][i][j] = telegram.InlineKeyboardButton(
                        '⭕️', callback_data=str(i * self.board_size + j))

        reply = InlineKeyboardMarkup(self.games5[id][1])

        if self.games5[id][0].board.move_count == 1 and self.games5[id][
                2] == gomokuboard.State.O:
            pass
        elif mc < self.games5[id][0].board.move_count:
            bot.editMessageText(
                chat_id=update.callback_query.message.chat_id,
                message_id=update.callback_query.message.message_id,
                text='Let\'s play, my dear opponent! ',
                reply_markup=reply)
Exemple #3
0
def setup(bot, update):
    # Se o setup for iniciado em um grupo
    if update.message.chat.type == 'group':
        # Se já houver uma entrada desse grupo na base de dados
        if database.confere_grupo(update.message.chat_id):
            msg = "Ops! Parece que esse grupo já possui uma entrada na base de dados..."
            bot.send_message(chat_id=update.message.chat_id, text=msg)
            msg = "Não se preocupe. A não ser que esse grupo seja recém-criado, não é um problema."
            bot.send_message(chat_id=update.message.chat_id, text=msg)
            msg = "Caso esse grupo seja recém-criado, use o comando /suporte, diga que recebeu essa mensagem, e resolveremos seu problema rapidinho."
            bot.send_message(chat_id=update.message.chat_id, text=msg)
            return ConversationHandler.END
        
        # Se o usuário for um administrador do grupo...
        if is_group_admin(bot, update.message.from_user.id, update.message.chat.id):
            msg = "As fichas de personagem associadas a esse grupo devem ficar abertas para edições?\n"
            # Cria um teclado para a resposta
            keyboard = [[telegram.InlineKeyboardButton("Sim", callback_data = "Sim")],
                        [telegram.InlineKeyboardButton("Não", callback_data = "Não")]]
            inline_kb_markup = telegram.InlineKeyboardMarkup(keyboard, resize_keyboard=True, one_time_keyboard=True)
            # Exibe o teclado
            bot.send_message(chat_id=update.message.chat_id, text=msg, reply_markup=inline_kb_markup)
            return SETUP_RESPOSTA
        # Se o setup não for iniciado/respondido por um usuário na lista de administradores.
        else:
            msg = "Desculpe, mas é preciso ser um administrador do grupo para concluir o setup."
            bot.send_message(chat_id=update.message.chat_id, text=msg)
    # Se o setup não for iniciado em um grupo
    else:
        msg = "Já que esse é um chat privado, não precisamos configurar nada relacionado a um grupo."
        bot.send_message(chat_id=update.message.chat_id, text=msg)
        return ConversationHandler.END
def delete_menu(torrent_id: int) -> Tuple[str, telegram.InlineKeyboardMarkup]:
    torrent = transClient.get_torrent(torrent_id)
    text = ("⚠️Do you really want to delete this torrent?⚠️\n"
            f"{torrent.name}\n"
            "You also can delete torrent with all downloaded data.")
    reply_markup = telegram.InlineKeyboardMarkup([
        [
            telegram.InlineKeyboardButton(
                "❌Yes❌",
                callback_data=f"deletetorrent_{torrent_id}",
            )
        ],
        [
            telegram.InlineKeyboardButton(
                "❌Yes, with data❌",
                callback_data=f"deletetorrent_{torrent_id}_data",
            )
        ],
        [
            telegram.InlineKeyboardButton(
                "⏪Back",
                callback_data=f"torrent_{torrent_id}",
            )
        ],
    ])
    return text, reply_markup
def select_files_add_menu(
        torrent_id: int) -> Tuple[str, telegram.InlineKeyboardMarkup]:
    SIZE_OF_LINE = 100
    KEYBORD_WIDTH = 5
    torrent = transClient.get_torrent(torrent_id)
    if len(torrent.name) >= SIZE_OF_LINE:
        name = f"{torrent.name[:SIZE_OF_LINE]}.."
    else:
        name = torrent.name
    text = f"*{escape_markdown(name, 2)}*\n"
    text += "Files:\n"
    column = 0
    row = 0
    file_keyboard: list[list[telegram.InlineKeyboardButton]] = [[]]
    for file_id, file in enumerate(torrent.files()):
        raw_name = file.name.split("/")
        filename = raw_name[1] if len(raw_name) == 2 else file.name
        if len(filename) >= SIZE_OF_LINE:
            filename = f"{filename[:SIZE_OF_LINE]}.."
        id = escape_markdown(f"{file_id+1}. ", 2)
        filename = escape_markdown(filename, 2, "PRE")
        file_size_raw = trans_utils.format_size(file.size)
        file_size = escape_markdown(
            f"{round(file_size_raw[0], 2)} {file_size_raw[1]}", 2)
        if column >= KEYBORD_WIDTH:
            file_keyboard.append([])
            column = 0
            row += 1
        if file.selected:
            text += f"*{id}*`{filename}`  {file_size}\n"
            button = telegram.InlineKeyboardButton(
                f"{file_id+1}. ✅",
                callback_data=f"fileselect_{torrent_id}_{file_id}_0",
            )
        else:
            text += f"*{id}*~{filename}~  {file_size}\n"
            button = telegram.InlineKeyboardButton(
                f"{file_id+1}. ❌",
                callback_data=f"fileselect_{torrent_id}_{file_id}_1",
            )
        column += 1
        file_keyboard[row].append(button)
    total_size = trans_utils.format_size(torrent.totalSize)
    size_when_done = trans_utils.format_size(torrent.sizeWhenDone)
    text += escape_markdown(
        f"Size to download: {round(size_when_done[0], 2)} {size_when_done[1]}"
        f" / {round(total_size[0], 2)} {total_size[1]}",
        2,
    )
    control_buttons = [
        [
            telegram.InlineKeyboardButton(
                "⏪Back",
                callback_data=f"addmenu_{torrent_id}",
            )
        ],
    ]
    reply_markup = telegram.InlineKeyboardMarkup(file_keyboard +
                                                 control_buttons)
    return text, reply_markup
Exemple #6
0
    def selectTerm(self, bot, update):
        keyboard = [
            [
                telegram.InlineKeyboardButton('Matriculas e Rematriculas',
                                              callback_data='date-matriculas'),
                telegram.InlineKeyboardButton('CCRs', callback_data='date-ccr')
            ],
            [
                telegram.InlineKeyboardButton('Aulas e Férias/Feriados',
                                              callback_data='date-aulas'),
                telegram.InlineKeyboardButton('ACCs', callback_data='date-acc')
            ],
            [
                telegram.InlineKeyboardButton('← Menu principal',
                                              callback_data='main-menu')
            ]
        ]

        replyMarkup = telegram.InlineKeyboardMarkup(keyboard)

        bot.editMessageText(
            message_id=update.callback_query.message.message_id,
            chat_id=update.callback_query.message.chat.id,
            text='*Selecione o Assunto:*',
            parse_mode='Markdown',
            reply_markup=replyMarkup)
Exemple #7
0
def start_query(bot, update):
    query = update.callback_query
    #take user's username
    user = "******".format(query.from_user.username)
    #message
    msg = "*WELCOME TO PUBG Host Bot*!\n"
    msg += "---------------------------------------\n"
    msg += "Hello User " + user + " ! 😆\n"
    msg += "My name Register Bot! You can register to me\n"
    msg += "with\n`/register [pubg ign]`.\n"
    msg += "\n"
    msg += "For more information📚, you can ask:\n"
    msg += "-> `@dharmaraj_24`\n"
    msg += "-> `@Asaf31214`\n"
    msg += "-> `@VrozAnims2003`\n"
    msg += "---------------------------------------\n"
    #send message to user
    button_list = [
        telegram.InlineKeyboardButton(
            emojize(":ledger: Command List :ledger:"),
            callback_data="command_list"),
        telegram.InlineKeyboardButton(
            emojize(":globe_with_meridians: About :globe_with_meridians:"),
            callback_data="about_query")
    ]

    reply_markup = telegram.InlineKeyboardMarkup(
        build_menu(button_list, n_cols=1))
    bot.edit_message_text(text=msg,
                          chat_id=query.message.chat_id,
                          message_id=query.message.message_id,
                          reply_markup=reply_markup,
                          parse_mode=telegram.ParseMode.MARKDOWN)
def SuggestionsMenu(suggestions, columns=2):
	rows = []
	full_rows = int(len(suggestions)/columns)
	buttons_last_row = len(suggestions) - full_rows*columns

	# Add the complete rows
	for row in range(full_rows):
		new_row = []
		this_row_suggestions = suggestions[row*columns:(row+1)*columns]
		for current_suggestion in this_row_suggestions:
			new_row.append(telegram.InlineKeyboardButton(current_suggestion,
				callback_data=current_suggestion))
		rows.append(new_row)

	# Add the last row
	last_row = []
	# Go <buttons_last_row> into the back of the list, and advance until the end of it.
	# (advance backwards because we're working with negative indexes --> back of the list)
	for i in range(buttons_last_row, 0, -1):
		last_row.append(telegram.InlineKeyboardButton(suggestions[-i],
			callback_data=suggestions[-i]))
	if len(last_row):
		rows.append(last_row)

	# Create the menu that this function will return (Inline Keyboard Markup)
	return telegram.InlineKeyboardMarkup(rows)
def QuantityMenu(sub, columns=2, quantities=[1, 5, 10, 20, 30, 50]):
	rows = [] # A certain amount of rows with full collumns, then add 1 row with the leftovers.
	full_rows = int(len(quantities)/columns)
	buttons_last_row = len(quantities) - full_rows*columns

	# Add the complete rows
	for row in range(full_rows):
		new_row = []
		this_row_quantities = quantities[row*columns:row*columns+columns]
		for current_quantity in this_row_quantities:
			new_row.append(telegram.InlineKeyboardButton(current_quantity, 
				callback_data="{} {}".format(sub, current_quantity)))
		rows.append(new_row)

	# Add the last row
	last_row = []
	# Go <buttons_last_row> into the back of the list, and advance until the end of it.
	# (advance backwards because we're working with negative indexes --> back of the list)
	for i in range(buttons_last_row, 0, -1):
		last_row.append(telegram.InlineKeyboardButton(quantities[-i], 
			callback_data="{} {}".format(sub, quantities[-i])))
	if len(last_row):
		rows.append(last_row)

	# Create the menu (inline keyboard Markup)
	return telegram.InlineKeyboardMarkup(rows)
Exemple #10
0
 def _reply_buttons(self):
     buttons = []
     if len(self.lang_keys) > 1:
         values = [
             (f'{value}' if value != self.lang_key else f'• {value}',
              f'{self.title}|{value}|0')
             for value in self.lang_keys
         ]
         for chunk in chunks(values, 4):
             buttons.append([
                 telegram.InlineKeyboardButton(text, callback_data=data)
                 for text, data in chunk
             ])
     if self.homonyms_count > 1:
         values = [
             (f'{i+1}' if i != self.homonym_index else f'• {i+1}',
              f'{self.title}|{self.lang_key}|{i}')
             for i in range(self.homonyms_count)
         ]
         for chunk in chunks(values, 6):
             buttons.append([
                 telegram.InlineKeyboardButton(text, callback_data=data)
                 for text, data in chunk
             ])
     if len(self.lang_keys) == 1 and self.homonyms_count == 1:
         buttons.append([
             telegram.InlineKeyboardButton(
                 'Обновить',
                 callback_data=f'{self.title}|{self.lang_keys[0]}|0'
             )
         ])
     return telegram.InlineKeyboardMarkup(buttons)
Exemple #11
0
 def build_chat_info_inline_keyboard(
         msg: EFBMsg,
         msg_template: str,
         reactions: str,
         reply_markup: Optional[telegram.InlineKeyboardMarkup],
         silent: bool = False) -> telegram.InlineKeyboardMarkup:
     """
     Build inline keyboard markup with message header and footer (reactions). Buttons are attached
     before any other commands attached.
     """
     description = [[
         telegram.InlineKeyboardButton(msg_template, callback_data="void")
     ]]
     if msg.text:
         description.append([
             telegram.InlineKeyboardButton(msg.text, callback_data="void")
         ])
     if reactions:
         description.append([
             telegram.InlineKeyboardButton(reactions, callback_data="void")
         ])
     sticker_reply_markup = reply_markup or telegram.InlineKeyboardMarkup(
         [])
     sticker_reply_markup.inline_keyboard = description + sticker_reply_markup.inline_keyboard
     return sticker_reply_markup
Exemple #12
0
def sendArea(bot, update):
    areas = db.orders.find()
    buts = None
    if len(list(db.orders.find())) == 0:
        bot.send_message(chat_id=update.message.chat_id,
                         text="Кладов по вашему городу нет")
        mainMenu(bot, update)
        return

    for x in areas:
        if buts == None:
            buts = [[
                telegram.InlineKeyboardButton(text=x['area'],
                                              callback_data=x['area'] +
                                              '$$AREA')
            ]]
        else:
            buts.append([
                telegram.InlineKeyboardButton(text=x['area'],
                                              callback_data=x['area'] +
                                              '$$AREA')
            ])

    bot.send_message(chat_id=update.message.chat_id,
                     text="🔸 Выберите регион 👇",
                     reply_markup=telegram.InlineKeyboardMarkup(buts))
Exemple #13
0
def generate_answer(bot, answer, update):
    """
    Interpret botkit answers and produce Telegram answers
    """
    for a in answer:
        if a['type'] == 'text':
            update.effective_message.reply_text(text=a['text'])
        if a['type'] == 'image':
            update.effective_message.reply_photo(photo=open(a['url'], 'rb'))
        if a['type'] == 'lyrics':
            update.effective_message.reply_text(text=a['lyrics'])
        if a['type'] == 'select':
            button_list = [
                telegram.InlineKeyboardButton(
                    text=option['text'],
                    callback_data='%s %s' % (option['intent'], option['text']))
                for option in a['select']
            ]
            reply_markup = telegram.InlineKeyboardMarkup(
                build_menu(button_list, n_cols=1))
            bot.send_message(chat_id=update.effective_message.chat.id,
                             text="What do you mean by %s?" %
                             (a['select'][0]['term']),
                             reply_markup=reply_markup)
        if a['type'] == 'link':
            button = [
                telegram.InlineKeyboardButton(text=a['title'], url=a['link'])
            ]
            reply_markup = telegram.InlineKeyboardMarkup(
                build_menu(button, n_cols=1))
            bot.send_message(chat_id=update.effective_message.chat.id,
                             text=a['text'],
                             reply_markup=reply_markup)
    def create_reply_markup(self, buttons):
        """
        Creates buttons (a.k.a custom keyboard)
        if there are not buttons it will remove the keyboard. 

        Parameters:
            button (list or list of lists) -- the keyboard 

        Note a list will organize the buttons vertically while a 
        list of list will be horizontal. You can mix the two as well
        """
        if buttons:
            button_list = []
            for rows in buttons:
                if isinstance(rows, list):
                    row = []
                    for col in rows:
                        row.append(telegram.InlineKeyboardButton(col))
                    button_list.append(row)

                else:
                    button_list.append([telegram.InlineKeyboardButton(rows)])
            return telegram.ReplyKeyboardMarkup(button_list)
        else:
            reply_markup = telegram.ReplyKeyboardRemove()
Exemple #15
0
def async_create_or_update_post(post, is_created):
    if not post.is_approved_by_moderator:
        send_telegram_message(
            chat=ADMIN_CHAT,
            text=render_html_message("moderator_post.html", post=post),
            reply_markup=telegram.InlineKeyboardMarkup(
                [[
                    telegram.InlineKeyboardButton(
                        "👍 Одобрить", callback_data=f"approve_post:{post.id}"),
                    telegram.InlineKeyboardButton(
                        "😕 Так себе", callback_data=f"forgive_post:{post.id}"),
                ],
                 [
                     telegram.InlineKeyboardButton(
                         "❌ В черновики",
                         callback_data=f"delete_post:{post.id}"),
                 ]]))

    # post to online channel
    send_telegram_message(
        chat=CLUB_ONLINE,
        text=render_html_message("channel_post_announce.html", post=post),
        parse_mode=telegram.ParseMode.HTML,
        disable_preview=True,
    )
Exemple #16
0
def send_row(update, context):
    config = get_config()

    path = config["cards_path"]
    chat_id = str(update.effective_message.chat_id)

    card = Card(f"{path}/{chat_id}/{context.user_data['card']}")
    row = card.choose_one()

    context.user_data["translate"] = row.original_lang  # Storage for next iter
    custom_keyboard = [[
        telegram.InlineKeyboardButton("Translate", callback_data="translate")
    ],
                       [
                           telegram.InlineKeyboardButton(
                               "↙️ Cards", callback_data="Cards"),
                           telegram.InlineKeyboardButton("🥐 View",
                                                         callback_data="View")
                       ]]
    reply_markup = telegram.InlineKeyboardMarkup(custom_keyboard)

    context.bot.edit_message_text(
        chat_id=update.callback_query.message.chat_id,
        message_id=update.callback_query.message.message_id,
        text=row.russian_lang,
        reply_markup=reply_markup)

    return
Exemple #17
0
def ant(bot, update):
    global chat
    usuario = update.callback_query.message.chat_id
    vetor = chat[usuario][0]
    cont = chat[usuario][1]
    ini = chat[usuario][2]
    if ini - 10 < 0:
        mini = 0
    else:
        mini = ini - 10
    for j in range(mini, ini):
        msg = vetor[j]
        bot.sendPhoto(chat_id=update.callback_query.message.chat_id,
                      photo=msg[1])
        bot.send_message(chat_id=update.callback_query.message.chat_id,
                         text=msg[0])
    chat[usuario][2] = mini
    chat[usuario][1] = j + 1

    keyboard = [[
        telegram.InlineKeyboardButton("Anteriores", callback_data='1')
    ], [telegram.InlineKeyboardButton("Próximas", callback_data='2')]]
    reply_markup = telegram.InlineKeyboardMarkup(keyboard)
    update.callback_query.message.reply_text(
        'Informe o ID da receita desejada ou escolha uma opção:',
        reply_markup=reply_markup)
Exemple #18
0
def duel(bot, update, real=False):
    msg = update.message.reply_to_message
    if msg == None:
        update.message.reply_text("用法:请使用此命令回复你想决斗的人")
        return
    from_user = update.message.from_user
    to_user = msg.from_user
    if to_user.is_bot:
        update.message.reply_text("你的决斗被Bot的林肯法球挡下了")
        return
    if real:
        accept_btn = telegram.InlineKeyboardButton(
            "接受",
            callback_data="real_duel:{},{}".format(from_user.id, to_user.id))
    else:
        accept_btn = telegram.InlineKeyboardButton(
            "接受", callback_data="duel:{},{}".format(from_user.id, to_user.id))
    decline_btn = telegram.InlineKeyboardButton(
        "拒绝/取消",
        callback_data="decline_duel:{},{}".format(from_user.id, to_user.id))
    btn_list = [[accept_btn, decline_btn]]
    markup = telegram.InlineKeyboardMarkup(btn_list)
    from_user_text = from_user.mention_markdown()
    if real:
        notif_text = "{} 向你发起了决斗!你可以选择在五分钟内接受或者无视这条信息\n **这将是一场生死对决**"
    else:
        notif_text = "{} 向你发起了决斗!你可以选择在五分钟内接受或者无视这条信息"
    notif = msg.reply_text(notif_text.format(from_user_text),
                           reply_markup=markup,
                           parse_mode="Markdown")

    def duel_expire(bot, job):
        notif.edit_text("决斗邀请已过期")

    queue.run_once(duel_expire, 300)
Exemple #19
0
def rebuild_inline_markup(reply_markup, context):
    if isinstance(reply_markup, telegram.InlineKeyboardMarkup):
        if octobot.Database.redis is None:
            return telegram.InlineKeyboardMarkup.from_button(
                telegram.InlineKeyboardButton(text=context.localize(
                    "Buttons are not available due to database error"),
                                              callback_data="nothing:")), None
        else:
            new_markup = []
            kbd_id = create_keyboard_id()
            for row in reply_markup.inline_keyboard:
                new_row = []
                for button in row:
                    if button.callback_data is not None:
                        new_row.append(
                            telegram.InlineKeyboardButton(
                                text=button.text,
                                callback_data=encode_callback_data(
                                    callback_data=button.callback_data,
                                    keyboard_id=kbd_id)))
                    else:
                        new_row.append(button)
                new_markup.append(new_row)
            octobot.Database.redis.expire(generate_inline_entry(kbd_id),
                                          60 * 60 * 24 * 7)
            return telegram.InlineKeyboardMarkup(new_markup), kbd_id
    else:
        return reply_markup, None
Exemple #20
0
def addquote(bot, update):
    msg = update.message.reply_to_message
    if msg == None:
        update.message.reply_text(
            "Usage:\n\nReplying to the message you wish to quote.")
        return
    key = "{}_{}".format(msg.chat.id, msg.message_id)
    if key in db["quotes"]:
        update.message.reply_text("Quote already added")
        return
    if key in pending_quote:
        update.message.reply_text("Quote already waiting for approval")
        return
    msg.quote_key = key
    content = "Pending Quote\nID:{}\n{}By {}:\n{}".format(
        msg.quote_key, get_quote_link(msg.quote_key), msg.from_user.full_name,
        msg.text or "[No Text Present]")
    appr_btn_list = [[
        telegram.InlineKeyboardButton(
            "Approve", callback_data="approve_quote:{}".format(key))
    ],
                     [
                         telegram.InlineKeyboardButton(
                             "Decline",
                             callback_data="decline_quote:{}".format(key))
                     ]]
    appr_markup = telegram.InlineKeyboardMarkup(appr_btn_list)
    for uid in quote_moderator:
        bot.send_message(uid, content, reply_markup=appr_markup)
    msg.prompt = update.message.reply_text("Quote pending approval.")
    pending_quote[key] = msg
Exemple #21
0
 def play_move(self, bot, update, id):
     """ Tictactoe """
     game = self.games[id]
     board_size = game[3]
     _board = BOARDS[board_size]
     mc = game[0].board.move_count
     if game[0].board.get_turn() == game[2]:
         self.get_player_move(bot, update, id)
     else:
         run_move(game)
     for i in range(board_size):
         for j in range(board_size):
             if game[0].board.board[i][j] == _board.State.X:
                 game[1][i][j] = telegram.InlineKeyboardButton(
                     "❌", callback_data=str(i * board_size + j))
             elif game[0].board.board[i][j] == _board.State.O:
                 game[1][i][j] = telegram.InlineKeyboardButton(
                     '⭕️', callback_data=str(i * board_size + j))
     reply = InlineKeyboardMarkup(game[1])
     if game[0].board.move_count == 1 and game[2] == _board.State.O:
         pass
     elif mc < game[0].board.move_count:
         bot.editMessageText(
             chat_id=update.callback_query.message.chat_id,
             message_id=update.callback_query.message.message_id,
             text='Let\'s play, Morty! ',
             reply_markup=reply)
Exemple #22
0
    def selectPeriod(self, bot, update):
        chat_id = update.callback_query.message.chat.id
        dailyButton = 'Diário'
        weeklyButton = 'Semanal'
        if self.isInDataBase(chat_id, 'daily'):
            dailyButton += ' ✔'
        if self.isInDataBase(chat_id, 'weekly'):
            weeklyButton += ' ✔'
        keyboard = [
            [
                telegram.InlineKeyboardButton(dailyButton,
                                              callback_data='daily'),
                telegram.InlineKeyboardButton(weeklyButton,
                                              callback_data='weekly')
            ],
            [
                telegram.InlineKeyboardButton('Desativar cardapio automático',
                                              callback_data='unsub')
            ],
            [
                telegram.InlineKeyboardButton('← Menu principal',
                                              callback_data='main-menu')
            ]
        ]

        replyMarkup = telegram.InlineKeyboardMarkup(keyboard)

        bot.editMessageText(
            message_id=update.callback_query.message.message_id,
            chat_id=chat_id,
            text='Selecione a periodicidade:',
            parse_mode='HTML',
            reply_markup=replyMarkup)
def add_menu(torrent_id: int) -> Tuple[str, telegram.InlineKeyboardMarkup]:
    torrent = transClient.get_torrent(torrent_id)
    text = "🆕__Adding torrent__🆕\n"
    text += f"*{escape_markdown(torrent.name, 2)}*\n"
    size_in_bytes = transClient.free_space(DISK)
    total_size = trans_utils.format_size(torrent.totalSize)
    size_when_done = trans_utils.format_size(torrent.sizeWhenDone)
    raw_text = (
        f"Size to download: {round(size_when_done[0], 2)} {size_when_done[1]}"
        f" / {round(total_size[0], 2)} {total_size[1]}\n")
    if size_in_bytes is not None:
        free_memory = trans_utils.format_size(size_in_bytes)
        raw_text += f"Free disk space: {round(free_memory[0], 2)} {free_memory[1]}\n"
    else:
        raw_text += "Could not get free disk space\n"
    text += escape_markdown(raw_text, 2)
    reply_markup = telegram.InlineKeyboardMarkup([
        [
            telegram.InlineKeyboardButton(
                "📂Files",
                callback_data=f"selectfiles_{torrent_id}",
            )
        ],
        [
            telegram.InlineKeyboardButton(
                "▶️Start",
                callback_data=f"torrentadd_{torrent_id}_start",
            ),
            telegram.InlineKeyboardButton(
                "❌Cancel",
                callback_data=f"torrentadd_{torrent_id}_cancel",
            ),
        ],
    ])
    return text, reply_markup
Exemple #24
0
def aboutTheBot(update, context):
    """Log Errors caused by Updates."""

    keyboard = [
        [
            telegram.InlineKeyboardButton(
                (emoji.emojize(":loop:", use_aliases=True)) + "Channel",
                url="t.me/theostrich"),
            telegram.InlineKeyboardButton("👥Support Group",
                                          callback_data='2'),
        ],
        [
            telegram.InlineKeyboardButton(
                (emoji.emojize(":bookmark:", use_aliases=True)) +
                "Add Me In Group",
                url="https://t.me/dwindle_Bot?startgroup=new")
        ],
    ]

    reply_markup = telegram.InlineKeyboardMarkup(keyboard)

    update.message.reply_text(
        "<b>Hey! My name is Dwindle.</b>"
        "\nI can handle links in different ways."
        "\n\n<b>About Me :</b>"
        "\n\n  - <b>Name</b>        : Dwindle"
        "\n\n  - <b>Creator</b>      : @theostrich"
        "\n\n  - <b>Language</b>  : Python 3"
        "\n\n  - <b>Library</b>       : <a href=\"https://github.com/python-telegram-bot/python-telegram-bot/\">python-telegram-bot</a>"
        "\n\n  - <b>Source Code</b>  : <a href=\"https://github.com/RabbitFored/Dwindle/\">Dwindle-Source</a>"
        "\n\nIf you enjoy using me and want to help me survive, do donate with the /donate command - my creator will be very grateful! Doesn't have to be much - every little helps! Thanks for reading :)",
        parse_mode='html',
        reply_markup=reply_markup,
        disable_web_page_preview=True)
Exemple #25
0
    def ttt3(self, bot, update):
        try:
            if update.message.text == "X":
                human_move = board.State.X
            elif update.message.text == 'O':
                human_move = board.State.O
        except:
            pass
        reply = telegram.ReplyKeyboardRemove()
        bot.send_message(chat_id=update.message.chat_id,
                         text='Preparing...',
                         reply_markup=reply)
        self.board_size = 3
        self.games[update.message.chat_id] = [
            console.Console(self.board_size), [], human_move
        ]

        for i in range(0, 9, 3):
            self.games[update.message.chat_id][1].append([
                telegram.InlineKeyboardButton(' ', callback_data=str(i)),
                telegram.InlineKeyboardButton(' ', callback_data=str(i + 1)),
                telegram.InlineKeyboardButton(' ', callback_data=str(i + 2))
            ])
        reply = InlineKeyboardMarkup(self.games[update.message.chat_id][1])

        if human_move == board.State.O:
            self.play_move(bot, update, update.message.chat_id)

        bot.send_message(chat_id=update.message.chat_id,
                         text='Let\'s play, my dear opponent! ',
                         reply_markup=reply)

        return 1
Exemple #26
0
def aboutTheBot(update, context):
    """Log Errors caused by Updates."""

    keyboard = [
        [
            telegram.InlineKeyboardButton(
                (emoji.emojize(":loop:", use_aliases=True)) + "Channel",
                url="t.me/OMG_info"),
            telegram.InlineKeyboardButton("👥Support Group",
                                          callback_data='2'),
        ],
        [
            telegram.InlineKeyboardButton(
                (emoji.emojize(":bookmark:", use_aliases=True)) +
                "Add Me In Group",
                url="https://t.me/dwindle_Bot?startgroup=new")
        ],
    ]

    reply_markup = telegram.InlineKeyboardMarkup(keyboard)

    update.message.reply_text(
        "<b>Hey! My name is TINY link.</b>"
        "\nI can handle links in different ways."
        "\n\n<b>About Me :</b>"
        "\n\n  - <b>Name</b>        : TINY link"
        "\n\n  - <b>Creator</b>      : @shado_hackers"
        "\n\n  - <b>Language</b>  : Python 3"
        "\n\n  - <b>support</b>       : <a href=\"https://t.me/OMG_info/\">OMG_info</a>"
        "\n\n  - <b>Follow</b>  : <a href=\"https://mobile.twitter.com/Lusifer_noob/\">Twitter</a>"
        "\n\nIf you enjoy using me and want to help me survive, do donate with the /donate command - my creator will be very grateful! Doesn't have to be much - every little helps! Thanks for reading :)",
        parse_mode='html',
        reply_markup=reply_markup,
        disable_web_page_preview=True)
Exemple #27
0
    def _cmd_central_heating_on(self, update: Update, context: CallbackContext) -> None:
        if self._is_modifying_heating:
            self._safe_send(chat_id(update),
                            _('Someone else is currently modifying the system configuration. Please try again later.'))
            return
        # Set flag to prevent other users from concurrently modifying heating
        self._is_modifying_heating = True
        # Parse optional duration parameter
        if len(context.args) > 0:
            duration = time_utils.parse_duration_input_str(context.args[0])
            if duration is None:
                self._safe_send(chat_id(update),
                                _('Duration parameter is invalid.'))
                return
            msg = _('Turn on heater for %(duration)s. Are you sure?',
                    duration=time_utils.format_timedelta(duration, small_space=False))
        else:
            duration = None
            msg = _('Turn on heater (must be stopped manually). Are you sure?')
        duration_str = '' if duration is None else CALLBACK_DELIMITER + time_utils.timedelta_hms_str(duration)

        keyboard = [[telegram.InlineKeyboardButton(_('Yes, sure!'),
                                                   callback_data=CALLBACK_HEATER_TURN_ON_CONFIRM + duration_str),
                     telegram.InlineKeyboardButton(_('No, cancel!'), callback_data=CALLBACK_HEATER_CANCEL)]]

        reply_markup = telegram.InlineKeyboardMarkup(keyboard)
        self._is_modifying_heating = self._safe_message_reply(update, msg, reply_markup=reply_markup)
Exemple #28
0
def order(bot, update):
    """
    Prints out the Buttons to select Drinks/Food

    Args:
        bot (telegram.Bot) - The bot that is running
        update (telegram.Update) - Incoming Update
        
    Return:
    """
    global foodDict, drinksDict
    foodDict = {}
    drinksDict = {}

    # Appends all types from json to variable types
    types = []
    with open(json_dir + 'menu.json') as f:
        data = json.load(f)
    for p in data:
        if p["types"] not in types:
            types.append(p["types"])

    # List of Buttons
    button_list = [
        telegram.InlineKeyboardButton(types[0], callback_data='pizzen'),
        telegram.InlineKeyboardButton(types[1], callback_data='getraenke')
    ]

    # Sending Message and ButtonList
    reply_markup = telegram.InlineKeyboardMarkup(
        build_menu(button_list, n_cols=2))
    bot.send_message(chat_id=update.message.chat.id,
                     text="Bitte wählen",
                     reply_markup=reply_markup)
Exemple #29
0
    def cmd_body(self):

        user = self.user
        match = user.get_match()
        board = match.get_board()
        # TODO: Check if Null

        # Check if it's the user's turn to move
        if not match.is_user_turn(user):
            user.send_message(constants.ERROR_TURN)
            return False

        move_result = game.check_move(board, user.pending_arg)
        if int(move_result) >= 0:
            accept_button = [[
                telegram.InlineKeyboardButton("Accept",
                                              callback_data='/accept'),
                telegram.InlineKeyboardButton("Cancel",
                                              callback_data='/cancel')
            ]]
            reply_markup = telegram.InlineKeyboardMarkup(accept_button)
            user.send_photo(photo=match.get_board_img(user, user.pending_arg),
                            caption="Do you want to confirm this move?",
                            reply_markup=reply_markup)

        return True
Exemple #30
0
def get_menu(data, columns=2):
    "Function to convert an array to Telegram InlineKeyboard."

    menu = []
    menu.append([])

    i = 0
    for option in enumerate(data):

        if not option[1]:
            # Insert blank elements to emulate a separator
            blank = (option[0] + 1) % columns
            while blank:
                menu.append([])
                blank -= 1

        elif re.search(r'^http:|https:.*', option[1][1]):

            menu[i].append(
                telegram.InlineKeyboardButton(option[1][0],
                                              url=option[1][1]))
        else:
            menu[i].append(
                telegram.InlineKeyboardButton(option[1][0],
                                              callback_data=option[1][1]))

        if not (option[0] + 1) % columns:
            menu.append([])
            i += 1

    return telegram.InlineKeyboardMarkup(menu)