def new_game(bot, update): """Handler for the /new command""" chat_id = update.message.chat_id if update.message.chat.type == 'private': help(bot, update) else: if update.message.chat_id in gm.remind_dict: for user in gm.remind_dict[update.message.chat_id]: send_async(bot, user, text=_("A new game has been started in {title}").format( title=update.message.chat.title)) del gm.remind_dict[update.message.chat_id] game = gm.new_game(update.message.chat) game.owner = update.message.from_user send_async(bot, chat_id, text=_("Created a new game! Join the game with /join " "and start the game with /start")) if botan: botan.track(update.message, 'New games')
def stats(bot, update): user = update.message.from_user us = UserSetting.get(id=user.id) if not us or not us.stats: send_async(bot, update.message.chat_id, text=_("You did not enable statistics. Use /settings in " "a private chat with the bot to enable them.")) else: stats_text = list() n = us.games_played stats_text.append( _("{number} game played", "{number} games played", n).format(number=n) ) n = us.first_places stats_text.append( _("{number} first place", "{number} first places", n).format(number=n) ) n = us.cards_played stats_text.append( _("{number} card played", "{number} cards played", n).format(number=n) ) send_async(bot, update.message.chat_id, text='\n'.join(stats_text))
def skip_player(bot, update): """Handler for the /skip command""" chat = update.message.chat user = update.message.from_user player = gm.player_for_user_in_chat(user, chat) if not player: send_async(bot, chat.id, text=_("You are not playing in a game in this chat.")) return game = player.game skipped_player = game.current_player next_player = game.current_player.next started = skipped_player.turn_started now = datetime.now() delta = (now - started).seconds if delta < skipped_player.waiting_time: send_async(bot, chat.id, text=_("Please wait {time} seconds") .format(time=(skipped_player.waiting_time - delta)), reply_to_message_id=update.message.message_id) elif skipped_player.waiting_time > 0: skipped_player.anti_cheat += 1 skipped_player.waiting_time -= 30 try: skipped_player.draw() except DeckEmptyError: pass send_async(bot, chat.id, text=__("Waiting time to skip this player has " "been reduced to {time} seconds.\n" "Next player: {name}", game.translate) .format(time=skipped_player.waiting_time, name=display_name(next_player.user))) game.turn() else: try: gm.leave_game(skipped_player.user, chat) send_async(bot, chat.id, text=__("{name1} was skipped four times in a row " "and has been removed from the game.\n" "Next player: {name2}", game.translate) .format(name1=display_name(skipped_player.user), name2=display_name(next_player.user))) except NotEnoughPlayersError: send_async(bot, chat.id, text=__("{name} was skipped four times in a row " "and has been removed from the game.\n" "The game ended.", game.translate) .format(name=display_name(skipped_player.user))) gm.end_game(chat.id, skipped_player.user)
def reset_waiting_time(bot, player): """Resets waiting time for a player and sends a notice to the group""" chat = player.game.chat if player.waiting_time < 90: player.waiting_time = 90 send_async(bot, chat.id, text=__("Waiting time for {name} has been reset to 90 " "seconds", multi=player.game.translate) .format(name=display_name(player.user)))
def locale_select(bot, update, groups): chat = update.message.chat user = update.message.from_user option = groups[0] if option in available_locales: us = UserSetting.get(id=user.id) us.lang = option _.push(option) send_async(bot, chat.id, text=_("Set locale!")) _.pop()
def notify_me(bot, update): """Handler for /notify_me command, pm people for next game""" chat_id = update.message.chat_id if update.message.chat.type == 'private': send_async(bot, chat_id, text=_("Send this command in a group to be notified " "when a new game is started there.")) else: try: gm.remind_dict[chat_id].add(update.message.from_user.id) except KeyError: gm.remind_dict[chat_id] = {update.message.from_user.id}
def do_call_bluff(bot, player): """Handles the bluff calling""" game = player.game chat = game.chat if player.prev.bluffing: send_async(bot, chat.id, text=__("Bluff called! Giving 4 cards to {name}", multi=game.translate) .format(name=player.prev.user.first_name)) try: player.prev.draw() except DeckEmptyError: send_async(bot, player.game.chat.id, text=__("There are no more cards in the deck.", multi=game.translate)) else: game.draw_counter += 2 send_async(bot, chat.id, text=__("{name1} didn't bluff! Giving 6 cards to {name2}", multi=game.translate) .format(name1=player.prev.user.first_name, name2=player.user.first_name)) try: player.draw() except DeckEmptyError: send_async(bot, player.game.chat.id, text=__("There are no more cards in the deck.", multi=game.translate)) game.turn()
def leave_game(bot, update): """Handler for the /leave command""" chat = update.message.chat user = update.message.from_user player = gm.player_for_user_in_chat(user, chat) if player is None: send_async(bot, chat.id, text=_("You are not playing in a game in " "this group."), reply_to_message_id=update.message.message_id) return game = player.game user = update.message.from_user try: gm.leave_game(user, chat) except NoGameInChatError: send_async(bot, chat.id, text=_("You are not playing in a game in " "this group."), reply_to_message_id=update.message.message_id) except NotEnoughPlayersError: gm.end_game(chat, user) send_async(bot, chat.id, text=__("Game ended!", multi=game.translate)) else: send_async(bot, chat.id, text=__("Okay. Next Player: {name}", multi=game.translate).format( name=display_name(game.current_player.user)), reply_to_message_id=update.message.message_id)
def new_game(bot, update): """Handler for the /new command""" chat_id = update.message.chat_id if update.message.chat.type == 'private': help(bot, update) else: game = gm.new_game(update.message.chat) game.owner = update.message.from_user send_async(bot, chat_id, text=_("Created a new game! Join the game with /join " "and start the game with /start")) if botan: botan.track(update.message, 'New games')
def do_draw(bot, player): """Does the drawing""" game = player.game draw_counter_before = game.draw_counter try: player.draw() except DeckEmptyError: send_async(bot, player.game.chat.id, text=__("There are no more cards in the deck.", multi=game.translate)) if (game.last_card.value == c.DRAW_TWO or game.last_card.special == c.DRAW_FOUR) and \ draw_counter_before > 0: game.turn()
def process_result(bot, update): """ Handler for chosen inline results. Checks the players actions and acts accordingly. """ try: user = update.chosen_inline_result.from_user player = gm.userid_current[user.id] game = player.game result_id = update.chosen_inline_result.result_id chat = game.chat except (KeyError, AttributeError): return logger.debug("Selected result: " + result_id) result_id, anti_cheat = result_id.split(':') last_anti_cheat = player.anti_cheat player.anti_cheat += 1 if result_id in ('hand', 'gameinfo', 'nogame'): return elif len(result_id) == 36: # UUID result return elif int(anti_cheat) != last_anti_cheat: send_async(bot, chat.id, text=__("Cheat attempt by {name}", multi=game.translate) .format(name=display_name(player.user))) return elif result_id == 'call_bluff': reset_waiting_time(bot, player) do_call_bluff(bot, player) elif result_id == 'draw': reset_waiting_time(bot, player) do_draw(bot, player) elif result_id == 'pass': game.turn() elif result_id in c.COLORS: game.choose_color(result_id) else: reset_waiting_time(bot, player) do_play_card(bot, player, result_id) if game in gm.chatid_games.get(chat.id, list()): send_async(bot, chat.id, text=__("Next player: {name}", multi=game.translate) .format(name=display_name(game.current_player.user)))
def status_update(bot, update): """Remove player from game if user leaves the group""" chat = update.message.chat if update.message.left_chat_member: user = update.message.left_chat_member try: gm.leave_game(user, chat) game = gm.player_for_user_in_chat(user, chat).game except NoGameInChatError: pass except NotEnoughPlayersError: gm.end_game(chat, user) send_async(bot, chat.id, text=__("Game ended!", game.translate)) else: send_async(bot, chat.id, text=__("Removing {name} from the game", game.translate) .format(name=display_name(user)))
def manageSubscribe(bot, update): chat_id = update.message.chat.id subscribes = r.table('users').get(chat_id).run(db) if subscribes is None: send_async(bot, chat_id, '您什么也没有订阅', reply_markup=ReplyKeyboardMarkup(keyboard=KB, one_time_keyboard=True)) return kb = [] for sub in subscribes['value']: q = r.table('traces').get(sub).run(db) kb.append(['[{0}] {1} ({2})'.format( q['com'], q['id'], STATES[q['state']] )]) kb.append([ '%s 查询/订阅快件' % Emoji.EYES, '%s 管理订阅' % Emoji.CLIPBOARD, ]) send_async(bot, chat_id, '以下的是您的订阅', reply_markup=ReplyKeyboardMarkup(keyboard=kb, one_time_keyboard=True))
def select_game(bot, update): """Handler for callback queries to select the current game""" chat_id = int(update.callback_query.data) user_id = update.callback_query.from_user.id players = gm.userid_players[user_id] for player in players: if player.game.chat.id == chat_id: gm.userid_current[user_id] = player break else: send_async(bot, update.callback_query.message.chat_id, text=_("Game not found.")) return @run_async def selected(bot): back = [[ InlineKeyboardButton(text=_("Back to last group"), switch_inline_query='') ]] bot.answerCallbackQuery( update.callback_query.id, text=_("Please switch to the group you selected!"), show_alert=False, timeout=TIMEOUT) bot.editMessageText( chat_id=update.callback_query.message.chat_id, message_id=update.callback_query.message.message_id, text=_("Selected group: {group}\n" "<b>Make sure that you switch to the correct " "group!</b>").format( group=gm.userid_current[user_id].game.chat.title), reply_markup=InlineKeyboardMarkup(back), parse_mode=ParseMode.HTML, timeout=TIMEOUT) selected(bot)
def kb_select(bot, update, groups): chat = update.message.chat user = update.message.from_user option = groups[0] if option == Emoji.BAR_CHART: us = UserSetting.get(id=user.id) us.stats = True send_async(bot, chat.id, text=_("Enabled statistics!")) elif option == Emoji.EARTH_GLOBE_EUROPE_AFRICA: kb = [[locale + ' - ' + descr] for locale, descr in sorted(available_locales.items())] send_async(bot, chat.id, text=_("Select locale"), reply_markup=ReplyKeyboardMarkup(keyboard=kb, one_time_keyboard=True)) elif option == Emoji.CROSS_MARK: us = UserSetting.get(id=user.id) us.stats = False us.first_places = 0 us.games_played = 0 us.cards_played = 0 send_async(bot, chat.id, text=_("Deleted and disabled statistics!"))
def kb_select(bot, update, groups): chat = update.message.chat user = update.message.from_user option = groups[0] if option == '📊': us = UserSetting.get(id=user.id) us.stats = True send_async(bot, chat.id, text=_("Enabled statistics!")) elif option == '🌍': kb = [[locale + ' - ' + descr] for locale, descr in sorted(available_locales.items())] send_async(bot, chat.id, text=_("Select locale"), reply_markup=ReplyKeyboardMarkup(keyboard=kb, one_time_keyboard=True)) elif option == '❌': us = UserSetting.get(id=user.id) us.stats = False us.first_places = 0 us.games_played = 0 us.cards_played = 0 us.last_places = 0 send_async(bot, chat.id, text=_("Deleted and disabled statistics!"))
def do_skip(bot, player, job_queue=None): game = player.game chat = game.chat skipped_player = game.current_player next_player = game.current_player.next if skipped_player.waiting_time > 0: skipped_player.anti_cheat += 1 skipped_player.waiting_time -= TIME_REMOVAL_AFTER_SKIP if (skipped_player.waiting_time < 0): skipped_player.waiting_time = 0 # if player get skipped after playing wildcard or +4 # before getting to choose color, then choose color randomly if game.choosing_color: game.last_card.color = random.choice(c.COLORS) try: skipped_player.draw() except DeckEmptyError: pass n = skipped_player.waiting_time send_async(bot, chat.id, text="Waiting time to skip this player has " "been reduced to {time} seconds.\n" "Next player: {name}".format(time=n, name=display_name( next_player.user))) logger.info( "{player} was skipped!. ".format(player=display_name(player.user))) game.turn() if job_queue: start_player_countdown(bot, game, job_queue) else: try: gm.leave_game(skipped_player.user, chat) send_async(bot, chat.id, text="{name1} ran out of time " "and has been removed from the game!\n" "Next player: {name2}".format( name1=display_name(skipped_player.user), name2=display_name(next_player.user))) logger.info("{player} was skipped!. ".format( player=display_name(player.user))) if job_queue: start_player_countdown(bot, game, job_queue) except NotEnoughPlayersError: send_async(bot, chat.id, text="{name} ran out of time " "and has been removed from the game!\n" "The game ended.".format( name=display_name(skipped_player.user))) gm.end_game(chat, skipped_player.user)
def close_game(bot, update): """Handler for the /close command""" chat = update.message.chat user = update.message.from_user games = gm.chatid_games.get(chat.id) if not games: send_async(bot, chat.id, text=_("There is no running game in this chat.")) return game = games[-1] if game.owner.id == user.id: game.open = False send_async(bot, chat.id, text=_("Closed the lobby. " "No more players can join this game.")) return else: send_async(bot, chat.id, text=_("Only the game creator ({name}) can do that.") .format(name=game.owner.first_name), reply_to_message_id=update.message.message_id) return
def do_play_card(bot, player, result_id): """Plays the selected card and sends an update to the group if needed""" card = c.from_str(result_id) player.play(card) game = player.game chat = game.chat user = player.user us = UserSetting.get(id=user.id) if not us: us = UserSetting(id=user.id) if us.stats: us.cards_played += 1 if game.choosing_color: send_async(bot, chat.id, text=_("Please choose a color")) if len(player.cards) == 1: send_async(bot, chat.id, text="UNO!") if len(player.cards) == 0: send_async(bot, chat.id, text=__("{name} won!", multi=game.translate) .format(name=user.first_name)) if us.stats: us.games_played += 1 if game.players_won is 0: us.first_places += 1 game.players_won += 1 try: gm.leave_game(user, chat) except NotEnoughPlayersError: send_async(bot, chat.id, text=__("Game ended!", multi=game.translate)) us2 = UserSetting.get(id=game.current_player.user.id) if us2 and us2.stats: us2.games_played += 1 gm.end_game(chat, user) if botan: botan.track(Message(randint(1, 1000000000), user, datetime.now(), Chat(chat.id, 'group')), 'Played cards')
def disable_translations(bot, update): """Handler for the /disable_translations command""" chat = update.message.chat user = update.message.from_user games = gm.chatid_games.get(chat.id) if not games: send_async(bot, chat.id, text=_("There is no running game in this chat.")) return game = games[-1] if game.owner.id == user.id: game.translate = False send_async(bot, chat.id, text=_("Disabled multi-translations. " "Enable them again with " "/enable_translations")) return else: send_async(bot, chat.id, text=_("Only the game creator ({name}) can do that") .format(name=game.owner.first_name), reply_to_message_id=update.message.message_id) return
def join_game(bot, update): """Handler for the /join command""" chat = update.message.chat if update.message.chat.type == 'private': help_handler(bot, update) return try: gm.join_game(update.message.from_user, chat) except LobbyClosedError: send_async(bot, chat.id, text="Gand maara madarjaat") except NoGameInChatError: send_async(bot, chat.id, text=_("No game is running at the moment. " "Create a new game with /new"), reply_to_message_id=update.message.message_id) except AlreadyJoinedError: send_async(bot, chat.id, text=_("You already joined the game. Start the game " "with /start"), reply_to_message_id=update.message.message_id) except DeckEmptyError: send_async(bot, chat.id, text=_("There are not enough cards left in the deck for " "new players to join."), reply_to_message_id=update.message.message_id) else: send_async(bot, chat.id, text=_("Joined the game"), reply_to_message_id=update.message.message_id)
def disable_translations(bot, update): """Handler for the /disable_translations command""" chat = update.message.chat user = update.message.from_user games = gm.chatid_games.get(chat.id) if not games: send_async(bot, chat.id, text=_("There is no running game in this chat.")) return game = games[-1] if user.id in game.owner: game.translate = False send_async(bot, chat.id, text=_("Disabled multi-translations. " "Enable them again with " "/enable_translations")) return else: send_async( bot, chat.id, text=_("Only the game creator ({name}) and admin can do that." ).format(name=game.starter.first_name), reply_to_message_id=update.message.message_id) return
def help_handler(bot, update): """Handler for the /help command""" help_text = _("Follow these steps:\n\n" "1. Add this bot to a group\n" "2. In the group, start a new game with /new or join an already" " running game with /join\n" "3. After at least two players have joined, start the game with" " /start\n" "4. Type <code>@unobot</code> into your chat box and hit " "<b>space</b>, or click the <code>via @unobot</code> text " "next to messages. You will see your cards (some greyed out), " "any extra options like drawing, and a <b>?</b> to see the " "current game state. The <b>greyed out cards</b> are those you " "<b>can not play</b> at the moment. Tap an option to execute " "the selected action.\n" "Players can join the game at any time. To leave a game, " "use /leave. If a player takes more than 90 seconds to play, " "you can use /skip to skip that player. Use /notify_me to " "receive a private message when a new game is started.\n\n" "<b>Language</b> and other settings: /settings\n" "Other commands (only game creator):\n" "/close - Close lobby\n" "/open - Open lobby\n" "/kill - Terminate the game\n" "/kick - Select a player to kick " "by replying to him or her\n" "/enable_translations - Translate relevant texts into all " "languages spoken in a game\n" "/disable_translations - Use English for those texts\n\n" "<b>Experimental:</b> Play in multiple groups at the same time. " "Press the <code>Current game: ...</code> button and select the " "group you want to play a card in.\n" "If you enjoy this bot, " "<a href=\"https://telegram.me/storebot?start=mau_mau_bot\">" "rate me</a>, join the " "<a href=\"https://telegram.me/unobotupdates\">update channel</a>" " and buy an UNO card game.") send_async(bot, update.message.chat_id, text=help_text, parse_mode=ParseMode.HTML, disable_web_page_preview=True)
def help(bot, update): chat_id = update.message.chat.id if user_action.get(chat_id) == 1: express_id = update.message.text user_action[chat_id] = express_id result = getDetail(express_id) if result == '快递单号不正确': send_async(bot, chat_id, result, reply_markup=ReplyKeyboardMarkup(keyboard=KB, one_time_keyboard=True)) return subscribes = r.table('users').get(chat_id).run(db) if subscribes is not None and express_id in subscribes['value']: kb = [ ['%s 取消对该快件的订阅' % Emoji.BELL_WITH_CANCELLATION_STROKE], [ '%s 查询/订阅快件' % Emoji.EYES, '%s 管理订阅' % Emoji.CLIPBOARD, ] ] else: kb = [ ['%s 订阅该快件' % Emoji.BELL], [ '%s 查询/订阅快件' % Emoji.EYES, '%s 管理订阅' % Emoji.CLIPBOARD, ] ] send_async(bot, chat_id, result, parse_mode='html', reply_markup=ReplyKeyboardMarkup( keyboard=kb, one_time_keyboard=True)) return send_async(bot, chat_id, '请按照下面的提示进行操作~', reply_markup=ReplyKeyboardMarkup(keyboard=KB, one_time_keyboard=True))
def open_game(bot, update): """Handler for the /open command""" chat = update.message.chat user = update.message.from_user games = gm.chatid_games.get(chat.id) if not games: send_async(bot, chat.id, text=_("There is no running game in this chat.")) return game = games[-1] if user.id in game.owner: game.open = True send_async(bot, chat.id, text=_("Opened the lobby. " "New players may /join the game.")) return else: send_async( bot, chat.id, text=_("Only the game creator ({name}) and admin can do that." ).format(name=game.starter.first_name), reply_to_message_id=update.message.message_id) return
def add_trigger(bot: Bot, update: Update): if update.message.from_user.id in get_admin_ids(bot, update.message.chat_id): msg = update.message.text.split(' ', 1) if len(msg) == 2 and len( msg[1]) > 0 or update.message.reply_to_message: trigger_text = msg[1].strip() trigger = Session.query(Trigger).filter_by( trigger=trigger_text).first() if trigger is None: data = update.message.reply_to_message add_trigger_db(data, trigger_text) send_async( bot, chat_id=update.message.chat.id, text='The trigger for the phrase "{}" is set.'.format( trigger_text)) else: send_async( bot, chat_id=update.message.chat.id, text='Trigger "{}" already exists, select another one.'. format(trigger_text)) else: send_async(bot, chat_id=update.message.chat.id, text='Your thoughts are not clear, try one more time')
def process_result(bot, update, job_queue): """ Handler for chosen inline results. Checks the players actions and acts accordingly. """ try: user = update.chosen_inline_result.from_user player = gm.userid_current[user.id] game = player.game result_id = update.chosen_inline_result.result_id chat = game.chat except (KeyError, AttributeError): return logger.debug("Selected result: " + result_id) result_id, anti_cheat = result_id.split(':') last_anti_cheat = player.anti_cheat player.anti_cheat += 1 if result_id in ('hand', 'gameinfo', 'nogame'): return elif result_id.startswith('mode_'): # First 5 characters are 'mode_', the rest is the gamemode. mode = result_id[5:] game.set_mode(mode) logger.info("Gamemode changed to {mode}".format(mode=mode)) send_async(bot, chat.id, text=__("Gamemode changed to {mode}".format(mode=mode))) return elif len(result_id) == 36: # UUID result return elif int(anti_cheat) != last_anti_cheat: send_async(bot, chat.id, text=__("Cheat attempt by {name}", multi=game.translate).format( name=display_name(player.user))) return elif result_id == 'call_bluff': reset_waiting_time(bot, player) do_call_bluff(bot, player) elif result_id == 'draw': reset_waiting_time(bot, player) do_draw(bot, player) elif result_id == 'pass': game.turn() elif result_id in c.COLORS: game.choose_color(result_id) else: reset_waiting_time(bot, player) do_play_card(bot, player, result_id) if game_is_running(game): send_async(bot, chat.id, text=__("Agla chu: {name}", multi=game.translate).format( name=display_name(game.current_player.user))) start_player_countdown(bot, game, job_queue)
def playBot(player, bot, chat, game, job_queue): print('bot vez') if len(player.playable_cards()) == 0: if player.drew: send_async(bot, chat.id, text='Pass') game.turn() else: n = game.draw_counter or 1 reset_waiting_time(bot, player) do_draw(bot, player) send_async(bot, chat.id, text='Drawing {number} card'.format(number=n), multi=game.translate) else: cardPla = player.playable_cards()[0] do_play_card(bot, player, str(cardPla)) bot.sendSticker(chat.id, sticker=c.STICKERS[str(cardPla)], timeout=TIMEOUT) play_next(game, bot, chat, job_queue)
def leave_game(bot, update): """Handler for the /leave command""" chat = update.message.chat user = update.message.from_user player = gm.player_for_user_in_chat(user, chat) if player is None: send_async(bot, chat.id, text=_("You are not playing in a game in " "this group."), reply_to_message_id=update.message.message_id) return game = player.game user = update.message.from_user try: if game.owner.id == user.id: game.owner = game.current_player.user send_async(bot, chat.id, text=("Assign game owner to {name}").format(name=display_name(game.current_player.user)), reply_to_message_id=update.message.message_id) gm.leave_game(user, chat) except NoGameInChatError: send_async(bot, chat.id, text=_("You are not playing in a game in " "this group."), reply_to_message_id=update.message.message_id) except NotEnoughPlayersError: gm.end_game(chat, user) send_async(bot, chat.id, text=__("Game ended!", multi=game.translate)) else: send_async(bot, chat.id, text=__("Okay. Next Player: {name}", multi=game.translate).format( name=display_name(game.current_player.user)), reply_to_message_id=update.message.message_id)
def do_call_bluff(bot, player): """Handles the bluff calling""" game = player.game chat = game.chat if player.prev.ai: send_async(bot, chat_id, text=__("Computer doesn't know bluffing yet", multi=game.translate)) return elif player.prev.bluffing: send_async(bot, chat.id, text=__("Bluff called! Giving 4 cards to {name}", multi=game.translate) .format(name=player.prev.user.first_name)) try: player.prev.draw() except DeckEmptyError: send_async(bot, player.game.chat.id, text=__("There are no more cards in the deck.", multi=game.translate)) else: game.draw_counter += 2 send_async(bot, chat.id, text=__("{name1} didn't bluff! Giving 6 cards to {name2}", multi=game.translate) .format(name1=player.prev.user.first_name, name2=player.user.first_name)) try: player.draw() except DeckEmptyError: send_async(bot, player.game.chat.id, text=__("There are no more cards in the deck.", multi=game.translate)) game.turn() ai_turn(bot, game)
def admin_panel(bot: Bot, update: Update): send_async(bot, chat_id=update.message.chat.id, text=("""Welcome commands: /enable_welcome — enable welcome message. /disable_welcome — disable welcome message. /set_welcome <text> — set welcome message. \ ->Can contain %username% — will be shown as @username, %ign% - will show user ingame name, \ if not set to First and Last name, or ID, using %last_name%, %first_name%, %id%. <-i don't think this still exists *deleted probably* /show_welcome — show welcome message. Trigger commands: Reply to a message or file with /set_trigger <trigger text> — \ set message to reply with on a trigger (only current chat) /del_trigger <trigger> — delete trigger. /list_triggers — show all triggers. Reply to a message or file with /set_global_trigger <trigger text> — \ set message to reply with on a trigger (all chats) /del_global_trigger <trigger> — delete trigger. Super administrator commands: /add_admin <user> — add administrator to current chat. /del_admin <user> — delete administrator from current chat. /list_admins — show list of current chat administrators. /enable_trigger — allow everyone to call trigger. /disable_trigger — forbid everyone to call trigger. /find <user> - Show user status by telegram user name *might be removed* /findc <ign> - Show user status by ingame name *might be removed* /findi <id> - Show user status by telegram uquique id *might be removed* Free text commands: allow everyone to trigger - Allow every member to call triggers prevent everyone from triggering - Allow only admins to call triggers allow everyone to pin - Allow all members to pin messages prevent everyone from pinning - Allow only admins to pin messages Reply any message with Pin to Pin it (admins always can do that, other members if its enabled) Reply any message with Pin and notify to pin and send notificaion Reply any message with Delete to delete it """))
def show_settings(bot, update): chat = update.message.chat if update.message.chat.type != 'private': send_async(bot, chat.id, text=_("Please edit your settings in a private chat with " "the bot.")) return us = UserSetting.get(id=update.message.from_user.id) if not us: us = UserSetting(id=update.message.from_user.id) if not us.stats: stats = Emoji.BAR_CHART + ' ' + _("Enable statistics") else: stats = Emoji.CROSS_MARK + ' ' + _("Delete all statistics") kb = [[stats], [Emoji.EARTH_GLOBE_EUROPE_AFRICA + ' ' + _("Language")]] send_async(bot, chat.id, text=Emoji.WRENCH + ' ' + _("Settings"), reply_markup=ReplyKeyboardMarkup(keyboard=kb, one_time_keyboard=True))
def show_settings(bot, update): chat = update.message.chat if update.message.chat.type != 'private': send_async(bot, chat.id, text=_("Please edit your settings in a private chat with " "the bot.")) return us = UserSetting.get(id=update.message.from_user.id) if not us: us = UserSetting(id=update.message.from_user.id) if not us.stats: stats = '📊' + ' ' + _("Enable statistics") else: stats = '❌' + ' ' + _("Delete all statistics") kb = [[stats], ['🌍' + ' ' + _("Language")]] send_async(bot, chat.id, text='🔧' + ' ' + _("Settings"), reply_markup=ReplyKeyboardMarkup(keyboard=kb, one_time_keyboard=True))
def stats(bot, update): user = update.message.from_user us = UserSetting.get(id=user.id) if not us or not us.stats: send_async(bot, update.message.chat_id, text=_("You did not enable statistics. Use /settings in " "a private chat with the bot to enable them.")) else: stats_text = list() n = us.games_played stats_text.append( _("{number} game played", "{number} games played", n).format(number=n)) n = us.first_places stats_text.append( _("{number} first place", "{number} first places", n).format(number=n)) n = (us.first_places / us.games_played) * 100 stats_text.append( _("{number}% win percentage", "{number}% win percentage", n).format(number=round(n, 2))) n = us.last_places stats_text.append( _("{number} last place", "{number} last places", n).format(number=n)) n = us.cards_played stats_text.append( _("{number} card played", "{number} cards played", n).format(number=n)) send_async(bot, update.message.chat_id, text='\n'.join(stats_text))
def do_call_bluff(bot, player): """Handles the bluff calling""" game = player.game chat = game.chat if player.prev.bluffing: send_async(bot, chat.id, text=__("Bluff called! Giving 4 cards to {name}", multi=game.translate).format( name=player.prev.user.first_name)) try: if game.draw_counter == 4: play.prev.draw() elif player.prev(): game.draw_counter = 4 player.prev.draw() game.draw_counter -= 4 player.draw() except DeckEmptyError: send_async(bot, player.game.chat.id, text=__("There are no more cards in the deck.", multi=game.translate)) else: game.draw_counter += 2 send_async(bot, chat.id, text=__( "{name1} didn't bluff! Giving {cards} cards to {name2}", multi=game.translate).format( name1=player.prev.user.first_name, cards=game.draw_counter, name2=player.user.first_name)) try: player.draw() except DeckEmptyError: send_async(bot, player.game.chat.id, text=__("There are no more cards in the deck.", multi=game.translate)) game.turn()
def del_admin(bot: Bot, update: Update): if update.message.from_user.id in get_admin_ids(bot, update.message.chat_id): msg = update.message.text.split(' ', 1)[1] if msg.find('@') != -1: msg = msg.replace('@', '') if msg != '': user = Session.query(User).filter_by(username=msg).first() if user is None: send_async(bot, chat_id=update.message.chat.id, text='No such user') else: del_adm(bot, update.message.chat.id, user, session) else: user = Session.query(User).filter_by(id=msg).first() if user is None: send_async(bot, chat_id=update.message.chat.id, text='No such user') else: del_adm(bot, update.message.chat.id, user)
def skip_player(bot, update): """Handler for the /skip command""" chat = update.message.chat user = update.message.from_user player = gm.player_for_user_in_chat(user, chat) if not player: send_async(bot, chat.id, text=_("You are not playing in a game in this chat.")) return game = player.game skipped_player = game.current_player started = skipped_player.turn_started now = datetime.now() delta = (now - started).seconds # You can't skip if the current player still has time left # You can skip yourself even if you have time left (you'll still draw) # Admin and creator can skip current player anytime if user.id in game.owner: do_skip(bot, player) elif delta < skipped_player.waiting_time and player != skipped_player: n = skipped_player.waiting_time - delta send_async(bot, chat.id, text=_("Please wait {time} second", "Please wait {time} seconds", n).format(time=n), reply_to_message_id=update.message.message_id) else: do_skip(bot, player)
def new_game(bot, update): #Start DB us = UserSetting.get(id=update.message.from_user.id) if not us: us = UserSetting(id=update.message.from_user.id) #Start DB """Handler for the /new command""" chat_id = update.message.chat_id if update.message.chat.type == 'private': help_handler(bot, update) else: if update.message.chat_id in gm.remind_dict: for user in gm.remind_dict[update.message.chat_id]: send_async( bot, user, text=_("A new game has been started in {title}").format( title=update.message.chat.title)) del gm.remind_dict[update.message.chat_id] game = gm.new_game(update.message.chat) game.starter = update.message.from_user game.owner.append(update.message.from_user.id) game.mode = DEFAULT_GAMEMODE send_async(bot, chat_id, text=_("Created a new game! Join the game with /join " "and start the game with /start"))
def select_game(bot, update): """Handler for callback queries to select the current game""" chat_id = int(update.callback_query.data) user_id = update.callback_query.from_user.id players = gm.userid_players[user_id] for player in players: if player.game.chat.id == chat_id: gm.userid_current[user_id] = player break else: send_async(bot, update.callback_query.message.chat_id, text=_("Game not found.")) return @run_async def selected(bot): back = [[InlineKeyboardButton(text=_("Back to last group"), switch_inline_query='')]] bot.answerCallbackQuery(update.callback_query.id, text=_("Please switch to the group you selected!"), show_alert=False, timeout=TIMEOUT) bot.editMessageText(chat_id=update.callback_query.message.chat_id, message_id=update.callback_query.message.message_id, text=_("Selected group: {group}\n" "<b>Make sure that you switch to the correct " "group!</b>").format( group=gm.userid_current[user_id].game.chat.title), reply_markup=InlineKeyboardMarkup(back), parse_mode=ParseMode.HTML, timeout=TIMEOUT) selected(bot)
def status_update(bot, update): """Remove player from game if user leaves the group""" chat = update.message.chat if update.message.left_chat_member: user = update.message.left_chat_member try: gm.leave_game(user, chat) game = gm.player_for_user_in_chat(user, chat).game except NoGameInChatError: pass except NotEnoughPlayersError: gm.end_game(chat, user) send_async(bot, chat.id, text=__("Game ended!", multi=game.translate)) else: send_async( bot, chat.id, text=__("Removing {name} from the game", multi=game.translate).format(name=display_name(user)))
def join_game(bot, update): """Handler for the /join command""" chat = update.message.chat if update.message.chat.type == 'private': help(bot, update) return try: gm.join_game(update.message.from_user, chat) except LobbyClosedError: send_async(bot, chat.id, text=_("The lobby is closed")) except NoGameInChatError: send_async(bot, chat.id, text=_("No game is running at the moment. " "Create a new game with /new"), reply_to_message_id=update.message.message_id) except AlreadyJoinedError: send_async(bot, chat.id, text=_("You already joined the game. Start the game " "with /start"), reply_to_message_id=update.message.message_id) except DeckEmptyError: send_async(bot, chat.id, text=_("There are not enough cards left in the deck for " "new players to join."), reply_to_message_id=update.message.message_id) else: send_async(bot, chat.id, text=_("Joined the game"), reply_to_message_id=update.message.message_id)
def do_skip(bot, player, job_queue=None): game = player.game chat = game.chat skipped_player = game.current_player next_player = game.current_player.next if skipped_player.waiting_time > 0: skipped_player.anti_cheat += 1 skipped_player.waiting_time -= TIME_REMOVAL_AFTER_SKIP if (skipped_player.waiting_time < 0): skipped_player.waiting_time = 0 try: skipped_player.draw() except DeckEmptyError: pass n = skipped_player.waiting_time send_async(bot, chat.id, text="Ye khiladi {time} seconds ke" "liye hilane gaya hain\n" "Agla chu: {name}".format(time=n, name=display_name( next_player.user))) logger.info( "{player} was skipped!. ".format(player=display_name(player.user))) game.turn() if job_queue: start_player_countdown(bot, game, job_queue) else: try: gm.leave_game(skipped_player.user, chat) send_async(bot, chat.id, text="{name1} ran out of time " "and has been removed from the game!\n" "Next player: {name2}".format( name1=display_name(skipped_player.user), name2=display_name(next_player.user))) logger.info("{player} was skipped!. ".format( player=display_name(player.user))) if job_queue: start_player_countdown(bot, game, job_queue) except NotEnoughPlayersError: send_async(bot, chat.id, text="{name} ran out of time " "and has been removed from the game!\n" "The game ended.".format( name=display_name(skipped_player.user))) gm.end_game(chat, skipped_player.user)
def kill_game(bot, update): """Handler for the /kill command""" chat = update.message.chat user = update.message.from_user games = gm.chatid_games.get(chat.id) if update.message.chat.type == 'private': help_handler(bot, update) return if not games: send_async(bot, chat.id, text=_("There is no running game in this chat.")) return game = games[-1] if user_is_creator_or_admin(user, game, bot, chat): try: gm.end_game(chat, user) send_async(bot, chat.id, text=__("Game ended!", multi=game.translate)) except NoGameInChatError: send_async( bot, chat.id, text=_( "The game is not started yet. " "Join the game with /gjoin and start the game with /gstart" ), reply_to_message_id=update.message.message_id) else: send_async( bot, chat.id, text=_("Only the game creator ({name}) and admin can do that." ).format(name=game.starter.first_name), reply_to_message_id=update.message.message_id)
def kill_game(bot, update): """Handler for the /kill command""" chat = update.message.chat user = update.message.from_user games = gm.chatid_games.get(chat.id) if update.message.chat.type == 'private': help_handler(bot, update) return if not games: send_async(bot, chat.id, text="Abe Bihari Game hi chalu nahi :|") return game = games[-1] if user_is_creator_or_admin(user, game, bot, chat): try: gm.end_game(chat, user) send_async(bot, chat.id, text=__("chalo hogaya aaj ka, back to bihar.", multi=game.translate)) except NoGameInChatError: send_async( bot, chat.id, text=_( "Kardi na bihari wali baat " "Join the game with /join and start the game with /start"), reply_to_message_id=update.message.message_id) else: send_async( bot, chat.id, text=_("Only the game creator ({name}) and admin can do that." ).format(name=game.starter.first_name), reply_to_message_id=update.message.message_id)
def unsubscribe(bot, update): chat_id = update.message.chat.id subscribes = r.table('users').get(chat_id).run(db) if subscribes is None: send_async(bot, chat_id, '取消订阅失败,您什么也没有订阅', reply_markup=ReplyKeyboardMarkup(keyboard=KB, one_time_keyboard=True)) elif user_action[chat_id] not in subscribes['value']: send_async(bot, chat_id, '取消订阅失败,您并没有订阅这个快件', reply_markup=ReplyKeyboardMarkup(keyboard=KB, one_time_keyboard=True)) else: subscribes['value'].remove(user_action[chat_id]) r.table('users').get(chat_id).update(subscribes).run(db) send_async(bot, chat_id, '取消订阅成功', reply_markup=ReplyKeyboardMarkup(keyboard=KB, one_time_keyboard=True))
def ban(bot: Bot, update: Update): if update.message.from_user.id in get_admin_ids(bot, update.message.chat_id): username, reason = update.message.text.split(' ', 2)[1:] username = username.replace('@', '') user = Session.query(User).filter_by(username=username).first() if user: banned = Session.query(Ban).filter_by(user_id=user.id).first() if banned: send_async( bot, chat_id=update.message.chat.id, text='This user is already banned. The reason is: .'. format(banned.to_date, banned.reason)) else: banned = Ban() banned.user_id = user.id banned.from_date = datetime.now() banned.to_date = datetime.max banned.reason = reason or 'Reason not specified' member = Session.query().filter_by(user_id=user.id).first() if member: Session.delete(member) admins = Session.query(Admin).filter_by(user_id=user.id).all() for admin in admins: Session.delete(admin) Session.add(banned) Session.commit() send_async(bot, chat_id=user.id, text='You were banned because: {}'.format( banned.reason)) send_async(bot, chat_id=update.message.chat.id, text='Soldier successfully banned') else: send_async(bot, chat_id=update.message.chat.id, text='No such user')
def do_call_bluff(bot, player): """Handles the bluff calling""" game = player.game chat = game.chat if player.prev.bluffing: send_async(bot, chat.id, text="{name} ne gaand di! Giving 4 cards".format( name=player.prev.user.first_name)) try: player.prev.draw() except DeckEmptyError: send_async(bot, player.game.chat.id, text=__("There are no more cards in the deck.", multi=game.translate)) else: game.draw_counter += 2 send_async( bot, chat.id, text= "{name1} ne gaand nahi di, ab {name2} ki gaand marega. Dukaan ka investment lelo" .format(name1=player.prev.user.first_name, name2=player.user.first_name)) try: player.draw() except DeckEmptyError: send_async(bot, player.game.chat.id, text=__("There are no more cards in the deck.", multi=game.translate)) game.turn()
def unban(bot: Bot, update: Update): if update.message.from_user.id in get_admin_ids(bot, update.message.chat_id): username = update.message.text.split(' ', 1)[1] username = username.replace('@', '') user = Session.query(User).filter_by(username=username).first() if user: banned = Session.query(Ban).filter_by(user_id=user.id).first() if banned: Session.delete(banned) Session.commit() send_async(bot, chat_id=user.id, text='We can talk again 🌚') send_async( bot, chat_id=update.message.chat.id, text='{} is no longer banned.'.format('@' + user.username)) else: send_async(bot, chat_id=update.message.chat.id, text='This soldier is not banned') else: send_async(bot, chat_id=update.message.chat.id, text='No such user')
def subscribe(bot, update): chat_id = update.message.chat.id subscribes = r.table('users').get(chat_id).run(db) if subscribes is None: r.table('users').insert({ 'id': chat_id, 'value': [user_action[chat_id]] }).run(db) send_async(bot, chat_id, '订阅成功,如果快件有更新您将会收到通知', reply_markup=ReplyKeyboardMarkup(keyboard=KB, one_time_keyboard=True)) elif user_action[chat_id] in subscribes['value']: send_async(bot, chat_id, '订阅失败,您已经订阅了该快件', reply_markup=ReplyKeyboardMarkup(keyboard=KB, one_time_keyboard=True)) else: subscribes['value'].append(user_action[chat_id]) r.table('users').get(chat_id).update(subscribes).run(db) send_async(bot, chat_id, '订阅成功,如果快件有更新您将会收到通知', reply_markup=ReplyKeyboardMarkup(keyboard=KB, one_time_keyboard=True))
def add_ai(bot, update): """ Handler for the /add_ai command """ chat_id = update.message.chat_id if update.message.chat.type == 'private': help(bot, update) else: try: game = gm.chatid_games[chat_id][-1] if not game.open: send_async(bot, chat_id, text="The lobby is closed") return else: Player(game, None, ai=True) send_async(bot, chat_id, text="Added computer player", reply_to_message_id=update.message.message_id) except (KeyError, IndexError): send_async(bot, chat_id, text="No game is running at the moment. " "Create a new game with /new", reply_to_message_id=update.message.message_id)
def news(bot, update): """Handler for the /news command""" send_async(bot, update.message.chat_id, text=_("All news here: https://telegram.me/unobotupdates"), disable_web_page_preview=True)
def start_game(bot, update, args): """Handler for the /start command""" if update.message.chat.type != 'private': chat = update.message.chat try: game = gm.chatid_games[chat.id][-1] except (KeyError, IndexError): send_async(bot, chat.id, text=_("There is no game running in this chat. Create " "a new one with /new")) return if game.started: send_async(bot, chat.id, text=_("The game has already started")) elif len(game.players) < 2: send_async(bot, chat.id, text=_("At least two players must /join the game " "before you can start it")) else: game.play_card(game.last_card) game.started = True first_message = ( __("First player: {name}\n" "Use /close to stop people from joining the game.\n" "Enable multi-translations with /enable_translations", multi=game.translate) .format(name=display_name(game.current_player.user))) @run_async def send_first(): """Send the first card and player""" bot.sendSticker(chat.id, sticker=c.STICKERS[str(game.last_card)], timeout=TIMEOUT) bot.sendMessage(chat.id, text=first_message, timeout=TIMEOUT) send_first() elif len(args) and args[0] == 'select': players = gm.userid_players[update.message.from_user.id] groups = list() for player in players: title = player.game.chat.title if player is gm.userid_current[update.message.from_user.id]: title = '- %s -' % player.game.chat.title groups.append( [InlineKeyboardButton(text=title, callback_data=str(player.game.chat.id))] ) send_async(bot, update.message.chat_id, text=_('Please select the group you want to play in.'), reply_markup=InlineKeyboardMarkup(groups)) else: help(bot, update)
def source(bot, update): """Handler for the /help command""" send_async(bot, update.message.chat_id, text=_(source_text) + '\n' + _(attributions), parse_mode=ParseMode.HTML, disable_web_page_preview=True)
def query(bot, update): chat_id = update.message.chat.id user_action[chat_id] = 1 send_async(bot, chat_id, '请输入您的快件单号')
def help(bot, update): """Handler for the /help command""" send_async(bot, update.message.chat_id, text=_(help_text), parse_mode=ParseMode.HTML, disable_web_page_preview=True)
"https://github.com/jh0ker/mau_mau_bot") attributions = ("Attributions:\n" 'Draw icon by ' '<a href="http://www.faithtoken.com/">Faithtoken</a>\n' 'Pass icon by ' '<a href="http://delapouite.com/">Delapouite</a>\n' "Originals available on http://game-icons.net\n" "Icons edited by ɳick") @user_locale def help(bot, update): """Handler for the /help command""" send_async(bot, update.message.chat_id, text=_(help_text), parse_mode=ParseMode.HTML, disable_web_page_preview=True) @user_locale def source(bot, update): """Handler for the /help command""" send_async(bot, update.message.chat_id, text=_(source_text) + '\n' + _(attributions), parse_mode=ParseMode.HTML, disable_web_page_preview=True) @user_locale def news(bot, update): """Handler for the /news command""" send_async(bot, update.message.chat_id, text=_("All news here: https://telegram.me/unobotupdates"), disable_web_page_preview=True)