def build_no_catch_message(bot, chat_id): player = DBAccessor.get_player(chat_id) if player is None: msg = bot.send_message( chat_id=chat_id, text='You\'re not on the list. Type /catch to get encounters.') elif not player.encounters: msg = bot.send_message( chat_id=chat_id, text='You\'re not on the list. Type /catch to get encounters.') player.messages_to_delete.append( Message.Message(_id=msg.message_id, _title=Constants.MESSAGE_TYPES.MENU_INFO_MSG, _time_sent=time.time())) update = DBAccessor.get_update_query_player( encounters=False, messages_to_delete=player.messages_to_delete) DBAccessor.update_player(player.chat_id, update) elif player.encounters: msg = bot.send_message( chat_id=chat_id, text='You\'re no longer on the list. Type /catch to get encounters.' ) player.messages_to_delete.append( Message.Message(_id=msg.message_id, _title=Constants.MESSAGE_TYPES.MENU_INFO_MSG, _time_sent=time.time())) update = DBAccessor.get_update_query_player( encounters=False, messages_to_delete=player.messages_to_delete) DBAccessor.update_player(player.chat_id, update) else: raise ('Data Error: Corrupt Player')
def send_approval_try(packet, sock, field_object_id, message_type, byte_packet, message, address): count = 0 while packet in order_packets: if count == 3: order_packets.remove(packet) now = datetime.now() dt_string = now.strftime("%H:%M:%S") console_messages.append( ( "[ " + dt_string + " ]" + " " + f"Soldier #{field_object_id} didn't approved the {message_type} <br />", Utility.MessageType.not_approved_message.value)) message = NotApprovedMessage(field_object_id, company_commander.get_company_num()) msg = Message(datetime.now().strftime("%H:%M:%S"), message) scenario.save_message(msg) logger.error("The packet '{}' didn't reached to Field {}".format(packet, get_field_address())) break sock.sendto(byte_packet, address) logger.debug("A Packet has been sent: {}".format(packet)) msg = Message(datetime.now().strftime("%H:%M:%S"), message) scenario.save_message(msg) count += 1 time.sleep(3)
def delete_friend(bot, chat_id, friend_to_be_deleted): keys = [[ InlineKeyboardButton( text='Sure, i dont like him/her anyway', callback_data=Constants.CALLBACK.FRIEND_CONFIRM_DELETE_YES( friend_to_be_deleted)) ], [ InlineKeyboardButton( text='No, just joking', callback_data=Constants.CALLBACK.FRIEND_CONFIRM_DELETE_NO) ]] reply_keyboard = InlineKeyboardMarkup(inline_keyboard=keys) msg = bot.send_message(chat_id=chat_id, text='You dont really want to loose a friend? o.o', reply_markup=reply_keyboard) player = DBAccessor.get_player(chat_id) player.messages_to_delete.append( Message.Message( msg.message_id, _title=Constants.MESSAGE_TYPES.FRIEND_CONFIRM_DELETE_MSG, _time_sent=time.time())) query = DBAccessor.get_update_query_player( messages_to_delete=player.messages_to_delete) DBAccessor.update_player(_id=player.chat_id, update=query)
def build_current_duel_status(bot, chat_id, duel: Duel.Duel): player = DBAccessor.get_player(chat_id) friend_id = duel.participant_1.player_id if duel.participant_1.player_id is not chat_id else duel.participant_2.player_id img = duel.get_img(player.chat_id) bio_player = BytesIO() bio_player.name = 'duel_img_' + str(player.chat_id) + '.png' img.save(bio_player, 'PNG') bio_player.seek(0) keys = [[ InlineKeyboardButton( text='Attack', callback_data=Constants.CALLBACK.DUEL_ACTION_ATTACK) ], [ InlineKeyboardButton( text='Nominate Champion', callback_data=Constants.CALLBACK.DUEL_ACTION_POKEMON) ], [ InlineKeyboardButton( text='Use Item', callback_data=Constants.CALLBACK.DUEL_ACTION_ITEM) ]] reply_markup = InlineKeyboardMarkup(inline_keyboard=keys) msg = bot.send_photo(chat_id=player.chat_id, text='Choose your action!', photo=bio_player, reply_markup=reply_markup) player.messages_to_delete.append( Message.Message(_id=msg.message_id, _title=Constants.MESSAGE_TYPES.DUEL_STATUS_MSG, _time_sent=time.time())) query = DBAccessor.get_update_query_player( messages_to_delete=player.messages_to_delete) DBAccessor.update_player(_id=player.chat_id, update=query)
def deserialize(json): try: player_id = json['player_id'] except KeyError as e: player_id = None logging.error(e) try: action = DuelAction.deserialize( json['action'] ) if json['action'] is not None else None except KeyError as e: action = None logging.error(e) try: team = [i for i in json['team']] if json['team'] is not None else None except KeyError as e: team = None logging.error(e) try: team_selection = Message.deserialize_msg( json['team_selection']) if json['team_selection'] is not None else None except KeyError as e: team_selection = None logging.error(e) try: pokemon = json['pokemon'] if json['pokemon'] is not None else None except KeyError as e: pokemon = None logging.error(e) return Participant(player_id=player_id, action=action, team=team, team_selection=team_selection, pokemon=pokemon)
def build_choose_friend_message(bot, chat_id, mode: Constants.CHOOSE_FRIEND_MODE): player = DBAccessor.get_player(chat_id) text_no_friends_base = 'Sadly, you got no friends :( Add some with their usernames using /addfriend.' if mode is Constants.CHOOSE_FRIEND_MODE.TRADE: type = Constants.MESSAGE_TYPES.TRADE_FRIENDLIST_MSG text_no_friends = 'You con only trade with friends.' + text_no_friends_base callback_build_function = Constants.CALLBACK.FRIEND_TRADE text_heading = 'Choose one of your friends to trade with:' elif mode is Constants.CHOOSE_FRIEND_MODE.DUEL: type = Constants.MESSAGE_TYPES.DUEL_FRIENDLIST_MSG text_no_friends = 'You con only challenge your friends.' + text_no_friends_base callback_build_function = Constants.CALLBACK.FRIEND_DUEL text_heading = 'Challenge one of your friends:' else: bot.send_message(chat_id=player.chat_id, text='Invalid friendlist mode, blame the devs!') raise ValueError('Invalid CHOOSE_FRIEND_MODE given!') if player is None: bot.send_message( chat_id=chat_id, text= 'You are not registered.\nType /username or /register to register.' ) return elif player.friendlist is None or len(player.friendlist) is 0: keys = [[ InlineKeyboardButton(text='Add friend', callback_data=Constants.CALLBACK.FRIEND_ADD) ]] reply_keyboard = InlineKeyboardMarkup(inline_keyboard=keys) bot.send_message(chat_id=player.chat_id, text=text_no_friends, reply_markup=reply_keyboard) return delete_messages_by_type(bot, player.chat_id, type=type) keys = [] for friend_id in player.friendlist: friend = DBAccessor.get_player(friend_id) if friend is None: continue else: keys.append([ InlineKeyboardButton( text=DBAccessor.get_player(friend_id).username, callback_data=callback_build_function(friend_id)) ], ) reply_keyboard = InlineKeyboardMarkup(inline_keyboard=keys) msg = bot.send_message(chat_id=player.chat_id, text=text_heading, reply_markup=reply_keyboard) player.messages_to_delete.append( Message.Message(msg.message_id, _title=type, _time_sent=time.time())) query = DBAccessor.get_update_query_player( messages_to_delete=player.messages_to_delete) DBAccessor.update_player(_id=player.chat_id, update=query)
def start_duel(bot, chat_id, event_id): keys = [[]] player = DBAccessor.get_player(chat_id) if len(player.pokemon_team) >= Constants.DUEL_MIN_POKEMON_PER_TEAM: keys[0].append( InlineKeyboardButton( text='Default', callback_data=Constants.CALLBACK.DUEL_START_DEFAULT(event_id))) text = 'Do you want to use your default team or a custom one?' elif len(player.pokemon_team) + len( player.pokemon) < Constants.DUEL_MIN_POKEMON_PER_TEAM: bot.send_message( chat_id=chat_id, text= 'You have not enough Pok\xe9mon to put a team for a duel. Go on catching!' ) return else: text = 'Your default team is not big enough, set up a custom team!' keys[0].append( InlineKeyboardButton( text='Custom', callback_data=Constants.CALLBACK.DUEL_START_CUSTOM(event_id))) reply_markup = InlineKeyboardMarkup(inline_keyboard=keys) msg = bot.send_message(chat_id=chat_id, text=text, reply_markup=reply_markup) player.messages_to_delete.append( Message.Message( _id=msg.message_id, _title=Constants.MESSAGE_TYPES.DUEL_TEAM_DEFAULT_CUSTOM, _time_sent=time.time())) query = DBAccessor.get_update_query_player( messages_to_delete=player.messages_to_delete) DBAccessor.update_player(chat_id, query)
def append_message_to_player(chat_id, message_id, type): player = DBAccessor.get_player(chat_id) player.messages_to_delete.append( Message.Message(message_id, type, time.time())) DBAccessor.update_player( chat_id, DBAccessor.get_update_query_player( messages_to_delete=player.messages_to_delete))
def build_msg_trade(bot, chat_id, player_id=None): if player_id is None: MessageHelper.build_choose_friend_message( bot=bot, chat_id=chat_id, mode=Constants.CHOOSE_FRIEND_MODE.TRADE) return else: player = DBAccessor.get_player(chat_id) friend = DBAccessor.get_player(int(player_id)) if player.trade is not None: bot.send_message(chat_id=player.chat_id, text='You are currently trading with {}'.format( DBAccessor.get_player( int(player.trade.partner_id)).username)) return if friend.trade is not None: bot.send_message( chat_id=player.chat_id, text='Your friend is currently trading with somebody else') return keys = [[ InlineKeyboardButton( text='Yes', callback_data=Constants.CALLBACK.TRADE_IVITE_CONFIRM( player.chat_id)), InlineKeyboardButton( text='No', callback_data=Constants.CALLBACK.TRADE_INVITE_DENY( player.chat_id)) ]] reply_keyboard = InlineKeyboardMarkup(inline_keyboard=keys) invite_msg = bot.send_message(chat_id=player_id, text='Your friend ' + str(player.username) + ' wants to trade. Are you interested?', reply_markup=reply_keyboard) friend.messages_to_delete.append( Message.Message(_id=invite_msg.message_id, _title=Constants.MESSAGE_TYPES.TRADE_INVITE_MSG, _time_sent=time.time())) query_friend = DBAccessor.get_update_query_player( messages_to_delete=friend.messages_to_delete) DBAccessor.update_player(_id=friend.chat_id, update=query_friend) player.trade = Trade(partner_id=friend.chat_id) query_player = DBAccessor.get_update_query_player(trade=player.trade) DBAccessor.update_player(_id=player.chat_id, update=query_player) msg = bot.send_message(chat_id=chat_id, text='Choose your Pokemon to trade:') MessageHelper.append_message_to_player( player.chat_id, message_id=msg.message_id, type=Constants.MESSAGE_TYPES.BAG_MSG) BagMessageBuilder.build_msg_bag(bot=bot, chat_id=player.chat_id, page_number=0, trade_mode=True)
def build_msg_duel_start_friend(bot, chat_id, friend_id): player = DBAccessor.get_player(chat_id) friend = DBAccessor.get_player(int(friend_id)) duel = DBAccessor.get_duel_by_participants(chat_id, friend_id) if duel is not None: bot.send_message(chat_id=player.chat_id, text='You are already dueling with {}'.format( friend.username)) build_msg_duel_active(bot=bot, chat_id=chat_id, duel_id=duel.event_id) elif len(player.pokemon_team) + len( player.pokemon) < Constants.DUEL_MIN_POKEMON_PER_TEAM: bot.send_message( chat_id=chat_id, text= 'You have not enough Pok\xe9mon to put a team for a duel. Go on catching!' ) return elif len(friend.pokemon_team) + len( friend.pokemon) < Constants.DUEL_MIN_POKEMON_PER_TEAM: bot.send_message( chat_id=friend_id, text= 'Your friend {} challenged you to a duel, but you have not enough ' 'Pok\xe9mon to put a team for a duel. Go on catching!'.format( player.username)) bot.send_message( chat_id=chat_id, text='Sadly, {} has not enough Pok\xe9mon to put a team for a duel.' .format(friend.username)) return else: keys = [[ InlineKeyboardButton( text='Yes', callback_data=Constants.CALLBACK.DUEL_INVITE_ACCEPT( player.chat_id)), InlineKeyboardButton( text='No', callback_data=Constants.CALLBACK.DUEL_INVITE_DENY( player.chat_id)) ]] reply_keyboard = InlineKeyboardMarkup(inline_keyboard=keys) invite_msg = bot.send_message( chat_id=friend_id, text='Your friend ' + str(player.username) + ' challenges you to a duel. Are you interested?', reply_markup=reply_keyboard) friend.messages_to_delete.append( Message.Message(_id=invite_msg.message_id, _title=Constants.MESSAGE_TYPES.DUEL_INVITE_MSG, _time_sent=time.time())) query_friend = DBAccessor.get_update_query_player( messages_to_delete=friend.messages_to_delete) DBAccessor.update_player(_id=friend.chat_id, update=query_friend) bot.send_message(chat_id=chat_id, text='...Awaiting {}\'s response...'.format( friend.username))
def build_catch_message(bot, chat_id): player = DBAccessor.get_player(chat_id) if player is None: player = Player.Player(chat_id, encounters=True) msg = bot.send_message( chat_id=chat_id, text='I will poke you, if you stumble over a pokemon.') player.messages_to_delete.append( Message.Message(_id=msg.message_id, _title=Constants.MESSAGE_TYPES.MENU_INFO_MSG, _time_sent=time.time())) DBAccessor.insert_new_player(player=player) elif not player.encounters: msg = bot.send_message( chat_id=chat_id, text= 'You are on the watch again. Type /nocatch to ignore encounters.') player.messages_to_delete.append( Message.Message(_id=msg.message_id, _title=Constants.MESSAGE_TYPES.MENU_INFO_MSG, _time_sent=time.time())) update = DBAccessor.get_update_query_player( encounters=True, messages_to_delete=player.messages_to_delete) DBAccessor.update_player(player.chat_id, update) elif player.encounters: msg = bot.send_message( chat_id=chat_id, text= 'I will notify as promised. Type /nocatch to ignore encounters.') player.messages_to_delete.append( Message.Message(_id=msg.message_id, _title=Constants.MESSAGE_TYPES.MENU_INFO_MSG, _time_sent=time.time())) update = DBAccessor.get_update_query_player( encounters=True, messages_to_delete=player.messages_to_delete) DBAccessor.update_player(player.chat_id, update) else: raise ('Data Error: Corrupt Player')
def send_team_selection(bot, chat_id, event_id: int, page_number: int): image, caption, reply_markup = build_team_selection( bot, chat_id, event_id, page_number) bio = BytesIO() bio.name = 'image_duel_team_' + str(chat_id) + '.png' image.save(bio, 'PNG') bio.seek(0) msg = bot.send_photo(chat_id=chat_id, photo=bio, caption=caption, parse_mode=ParseMode.MARKDOWN, reply_markup=reply_markup) player = DBAccessor.get_player(chat_id) player.messages_to_delete.append( Message.Message(_id=msg.message_id, _title=Constants.MESSAGE_TYPES.DUEL_TEAM_MSG, _time_sent=time.time())) update = DBAccessor.get_update_query_player( messages_to_delete=player.messages_to_delete) DBAccessor.update_player(chat_id, update=update) duel = DBAccessor.get_duel_by_id(int(event_id)) duel.get_participant_by_id(chat_id).team_selection = Message.Message( _id=msg.message_id, _title=Constants.MESSAGE_TYPES.DUEL_TEAM_MSG, _time_sent=time.time()) if chat_id == duel.participant_1.player_id: update_duel = DBAccessor.get_update_query_duel( participant_1=duel.participant_1) elif chat_id == duel.participant_2.player_id: update_duel = DBAccessor.get_update_query_duel( participant_2=duel.participant_2) else: raise ValueError( 'Participant not found! Chat_id: {} Event_id: {} '.format( chat_id, event_id)) DBAccessor.update_duel(event_id, update_duel)
def build_poke_display(bot, chat_id, trade_mode, page_num, poke_id): page_num = int(page_num) trade_mode = bool(int(trade_mode)) player = DBAccessor.get_player(chat_id) pokemon = DBAccessor.get_pokemon_by_id(int(poke_id)) # Delete msgs MessageHelper.delete_messages_by_type(bot, chat_id, Constants.MESSAGE_TYPES.BAG_MSG) MessageHelper.delete_messages_by_type( bot, chat_id, Constants.MESSAGE_TYPES.POKE_DISPLAY_MSG) text = 'Pokedex ID: ' + str(pokemon.pokedex_id) + '\n' + \ 'Name: ' + str(pokemon.name) + '\n' + \ 'Level: ' + str(pokemon.level) + '\n' bio = BytesIO() bio.name = 'image_displ_' + str(chat_id) + '.png' image = Pokemon.get_pokemon_portrait_image( pokemon_sprite=pokemon.sprites['front']) image.save(bio, 'PNG') bio.seek(0) reply_keyboard = get_display_keyboard_editing( poke_id=pokemon.poke_id, page_num=page_num) if not trade_mode else get_display_keyboard_trading( poke_id=pokemon.poke_id, page_num=page_num) try: msg = bot.send_photo(chat_id=chat_id, photo=bio, caption=text, parse_mode=ParseMode.MARKDOWN, reply_markup=reply_keyboard) player.messages_to_delete.append( Message.Message(_id=msg.message_id, _title=Constants.MESSAGE_TYPES.POKE_DISPLAY_MSG, _time_sent=time.time())) update = DBAccessor.get_update_query_player( messages_to_delete=player.messages_to_delete) DBAccessor.update_player(_id=player.chat_id, update=update) except ConnectionResetError as e: logging.error(e)
def send_menu_message(bot, update): player = DBAccessor.get_player(update.message.chat_id) if player is not None: MessageHelper.delete_messages_by_type( bot=bot, chat_id=update.message.chat_id, type=Constants.MESSAGE_TYPES.MENU_MSG) else: msg = bot.send_message( chat_id=update.message.chat_id, text= 'I do not know you yet. To be recognized next time, type /catch\n' 'This will enable encounters as well.') return text, reply_markup = build_msg_menu( player.chat_id, player.encounters if player is not None else False, trade=player.trade, duels=player.duels) msg = bot.send_message(chat_id=update.message.chat_id, text=text, reply_markup=reply_markup) if player is None: new_player = Player.Player( update.message.chat_id, messages_to_delete=[ Message.Message(_id=msg.message_id, _title=Constants.MESSAGE_TYPES.MENU_MSG, _time_sent=time.time()) ], encounters=False) DBAccessor.insert_new_player(new_player) else: MessageHelper.append_message_to_player( player.chat_id, msg.message_id, Constants.MESSAGE_TYPES.MENU_MSG)
def build_friendlist_message(bot, chat_id): player = DBAccessor.get_player(chat_id) if player is None: bot.send_message( chat_id=chat_id, text= 'You are not registered.\nType /username or /register to register.' ) return elif player.friendlist is None or len(player.friendlist) is 0: keys = [[ InlineKeyboardButton(text='Add friend', callback_data=Constants.CALLBACK.FRIEND_ADD) ]] reply_keyboard = InlineKeyboardMarkup(inline_keyboard=keys) bot.send_message( chat_id=chat_id, text= 'You got no friends :( Add some with their usernames using /addfriend.', reply_markup=reply_keyboard) return for i in player.get_messages(Constants.MESSAGE_TYPES.FRIENDLIST_MSG): try: bot.delete_message(chat_id=player.chat_id, message_id=i._id) except telegram.error.BadRequest as e: logging.error(e) x_mark = emojize(":x:", use_aliases=True) keys = [] for friend_id in player.friendlist: friend = DBAccessor.get_player(friend_id) if friend is None: continue else: keys.append([ InlineKeyboardButton( text=DBAccessor.get_player(friend_id).username, callback_data=Constants.CALLBACK.FRIEND_NAME), InlineKeyboardButton( text='Trade', callback_data=Constants.CALLBACK.FRIEND_TRADE(friend_id)), InlineKeyboardButton( text='Duel', callback_data=Constants.CALLBACK.FRIEND_DUEL(friend_id)), InlineKeyboardButton( text=x_mark, callback_data=Constants.CALLBACK.FRIEND_DELETE(friend_id)) ], ) keys.append([ InlineKeyboardButton(text='Add friend', callback_data=Constants.CALLBACK.FRIEND_ADD) ]) reply_keyboard = InlineKeyboardMarkup(inline_keyboard=keys) msg = bot.send_message(chat_id=player.chat_id, text='Your friends:', reply_markup=reply_keyboard) player.messages_to_delete.append( Message.Message(msg.message_id, _title=Constants.MESSAGE_TYPES.FRIENDLIST_MSG, _time_sent=time.time())) query = DBAccessor.get_update_query_player( messages_to_delete=player.messages_to_delete) DBAccessor.update_player(_id=player.chat_id, update=query)
def trade_pokemon_chosen(bot, chat_id, pokemon_id): pokemon_id = int(pokemon_id) player = DBAccessor.get_player(_id=chat_id) MessageHelper.delete_messages_by_type( bot, player.chat_id, Constants.MESSAGE_TYPES.POKE_DISPLAY_MSG) if player.trade.pokemon is not None and player.trade.pokemon.poke_id == pokemon_id: pass elif player.trade is not None: player.trade.pokemon = DBAccessor.get_pokemon_by_id(pokemon_id) player.pokemon.remove(pokemon_id) else: bot.send_message(chat_id=player.chat_id, text='Your trade exceeded.') return if player.trade.pokemon is None: bot.send_message(chat_id=player.chat_id, text='Pokemon not found, im getting old :/') return query = DBAccessor.get_update_query_player(pokemon=player.pokemon, trade=player.trade) DBAccessor.update_player(_id=player.chat_id, update=query) bot.send_message(chat_id=player.chat_id, text='You chose {} for this trade'.format( player.trade.pokemon.name)) partner = DBAccessor.get_player(int(player.trade.partner_id)) if partner.trade is not None: if partner.trade.pokemon is not None: image_player = Pokemon.build_pokemon_trade_image( player.trade.pokemon.sprites['back'], partner.trade.pokemon.sprites['front']) bio_player = BytesIO() bio_player.name = 'trade_img_' + str(player.chat_id) + '.png' image_player.save(bio_player, 'PNG') bio_player.seek(0) image_partner = Pokemon.build_pokemon_trade_image( partner.trade.pokemon.sprites['back'], player.trade.pokemon.sprites['front']) bio_partner = BytesIO() bio_partner.name = 'trade_img_' + str(partner.chat_id) + '.png' image_partner.save(bio_partner, 'PNG') bio_partner.seek(0) keys = [[ InlineKeyboardButton( text='Yes', callback_data=Constants.CALLBACK.TRADE_ACCEPT), InlineKeyboardButton( text='Nope and abort', callback_data=Constants.CALLBACK.TRADE_ABORT) ]] reply_markup = InlineKeyboardMarkup(inline_keyboard=keys) msg_play = bot.send_photo( chat_id=player.chat_id, caption='Both of you have chosen. ' '{} will entrust {} to you, you will part with {} ' 'in exchange. Do you accept this trade?'.format( partner.username, partner.trade.pokemon.name, player.trade.pokemon.name), photo=bio_player, reply_markup=reply_markup) msg_part = bot.send_photo( chat_id=partner.chat_id, caption='Both of you have chosen. ' '{} will entrust {} to you, you will part with {} ' 'in exchange. Do you accept this trade?'.format( player.username, player.trade.pokemon.name, partner.trade.pokemon.name), photo=bio_partner, reply_markup=reply_markup) player.messages_to_delete.append( Message.Message(msg_play.message_id, Constants.MESSAGE_TYPES.TRADE_CONFIRM_MSG, time.time())) partner.messages_to_delete.append( Message.Message(msg_part.message_id, Constants.MESSAGE_TYPES.TRADE_CONFIRM_MSG, time.time())) DBAccessor.update_player( player.chat_id, DBAccessor.get_update_query_player( messages_to_delete=player.messages_to_delete)) DBAccessor.update_player( partner.chat_id, DBAccessor.get_update_query_player( messages_to_delete=partner.messages_to_delete)) return bot.send_message( chat_id=player.chat_id, text='{} has not chosen yet. I will notify you when he/she is ready.'. format(partner.username)) bot.send_message( chat_id=partner.chat_id, text='Your trading partner has chosen {} to trade.'.format( player.trade.pokemon.name))
def deserialize_player(json): # FIXME: ugly code try: chat_id = json['_id'] except KeyError as e: chat_id = None logging.error(e) try: username = json['username'] except KeyError as e: username = None logging.error(e) try: friendlist = [i for i in json['friendlist']] except KeyError as e: friendlist = None logging.error(e) try: items = json['items'] except KeyError as e: items = None logging.error(e) try: pokemon = [i for i in json['pokemon']] except KeyError as e: pokemon = None logging.error(e) try: pokemon_team = [i for i in json['pokemon_team']] except KeyError as e: pokemon_team = None logging.error(e) try: last_encounter = json['last_encounter'] except KeyError as e: last_encounter = None logging.error(e) try: nc_msg_state = json['nc_msg_state'] except KeyError as e: nc_msg_state = None logging.error(e) try: edit_pokemon_id = json['edit_pokemon_id'] except KeyError as e: edit_pokemon_id = None logging.error(e) try: lang = json['lang'] except KeyError as e: lang = None logging.error(e) try: encounters = json['encounters'] except KeyError as e: encounters = None logging.error(e) try: messages_to_delete = [ Message.deserialize_msg(i) for i in json['messages_to_delete'] ] except KeyError as e: messages_to_delete = None logging.error(e) try: encounter = Encounter.deserialize( json['encounter']) if json['encounter'] is not None else None except KeyError as e: encounter = None logging.error(e) try: trade = Trade.deserialize( json['trade']) if json['trade'] is not None else None except KeyError as e: trade = None logging.error(e) try: duels = [i for i in json['duels']] except KeyError as e: duels = None logging.error(e) player = Player(chat_id=chat_id, username=username, friendlist=friendlist, items=items, pokemon=pokemon, pokemon_team=pokemon_team, last_encounter=last_encounter, nc_msg_state=nc_msg_state, edit_pokemon_id=edit_pokemon_id, lang=lang, encounters=encounters, messages_to_delete=messages_to_delete, encounter=encounter, trade=trade, duels=duels) return player
def build_msg_bag(bot, chat_id, trade_mode, page_number): page_number = int(page_number) trade_mode = bool(int(trade_mode)) pokecount = 8 player = DBAccessor.get_player(chat_id) if player is None: bot.send_message( chat_id=chat_id, text= 'I have not met you yet. Want to be a Pok\xe9mon trainer? Type /catch.' ) return pokelist = player.pokemon_team + player.pokemon pokemon_sprite_list = [] caption = '' if len(pokelist) > pokecount: caption = '*Page Number: *' + str(page_number) + ' Pok\xe9 ' + str( (page_number * pokecount) + 1) + '-' + (str((page_number + 1) * pokecount) if (page_number + 1) * pokecount <= len(pokelist) else str(len(pokelist))) + '/' + str(len(pokelist)) + '\n' list_start = pokecount * page_number list_end = pokecount * (page_number + 1) if len( pokelist) >= pokecount * (page_number + 1) else len(pokelist) page_list = pokelist[list_start:list_end] keys = [] for pokemon_id in page_list: pokemon = DBAccessor.get_pokemon_by_id(pokemon_id) if pokemon is None: logging.error('Pokemon with id {} None!'.format(pokemon)) pokelist.remove(pokemon_id) DBAccessor.update_player( chat_id, DBAccessor.get_update_query_player(pokelist)) keys.append([ InlineKeyboardButton( text=pokemon.name, callback_data=Constants.CALLBACK.POKE_DISPLAY_CONFIG( trade_mode=trade_mode, page_number=page_number, pokemon_id=pokemon.poke_id)) ]) pokemon_sprite_list.append(pokemon.sprites['front']) image = Pokemon.build_pokemon_bag_image(pokemon_sprite_list) MessageHelper.delete_messages_by_type( bot=bot, chat_id=chat_id, type=Constants.MESSAGE_TYPES.POKE_DISPLAY_MSG) MessageHelper.delete_messages_by_type(bot=bot, chat_id=chat_id, type=Constants.MESSAGE_TYPES.BAG_MSG) if image is not None: bio = BytesIO() bio.name = 'image_bag_' + str(chat_id) + '.png' image.save(bio, 'PNG') bio.seek(0) keys.append([]) if page_number > 0: keys[-1].append( InlineKeyboardButton(text='\u2190', callback_data=Constants.CALLBACK.BAG_PAGE( trade_mode, page_number - 1))) if len(pokelist) > list_end: keys[-1].append( InlineKeyboardButton(text='\u2192', callback_data=Constants.CALLBACK.BAG_PAGE( trade_mode, page_number + 1))) reply_markup = InlineKeyboardMarkup(inline_keyboard=keys) msg = bot.send_photo(chat_id=chat_id, photo=bio, reply_markup=reply_markup, caption=caption, parse_mode=ParseMode.MARKDOWN) else: msg = bot.send_message(chat_id=chat_id, text='Your bag is empty, catch some pokemon!') player.messages_to_delete.append( Message.Message(_id=msg.message_id, _title=Constants.MESSAGE_TYPES.BAG_MSG, _time_sent=time.time())) update = DBAccessor.get_update_query_player( messages_to_delete=player.messages_to_delete) DBAccessor.update_player(_id=player.chat_id, update=update)
def build_encounter_message(bot): logging.info('Encounter') cursor = DBAccessor.get_encounter_players_cursor() for player in cursor: draw = random.random() now = time.time() last_enc = float(player.last_encounter) if player.encounter is not None: if now - last_enc >= 900: # Reset player's catch state for i in player.get_messages( Constants.MESSAGE_TYPES.ENCOUNTER_MSG): try: bot.delete_message(chat_id=player.chat_id, message_id=i._id) except telegram.error.BadRequest as e: logging.error(e) query = { '$set': { 'last_encounter': now }, '$unset': { 'encounter': 1 } } DBAccessor.update_player(_id=player.chat_id, update=query) logging.info('reset encounter for player ' + str(player.chat_id)) continue chance = pow(1 / (24 * 60 * 60) * (now - last_enc), math.e) if 0 < draw < chance: pokemon_name = EichState.names_dict['pokenames'][random.choice( list(EichState.names_dict['pokenames'].keys()))] pokemon_direction = random.randint(0, 8) pokemon = Pokemon.get_random_poke( Pokemon.get_pokemon_json(pokemon_name), 10) keys = [[ InlineKeyboardButton( text='\u2196', callback_data=Constants.CALLBACK.CATCH(0)), InlineKeyboardButton( text='\u2191', callback_data=Constants.CALLBACK.CATCH(1)), InlineKeyboardButton(text='\u2197', callback_data=Constants.CALLBACK.CATCH(2)) ], [ InlineKeyboardButton( text='\u2190', callback_data=Constants.CALLBACK.CATCH(3)), InlineKeyboardButton( text='o', callback_data=Constants.CALLBACK.CATCH(4)), InlineKeyboardButton( text='\u2192', callback_data=Constants.CALLBACK.CATCH(5)) ], [ InlineKeyboardButton( text='\u2199', callback_data=Constants.CALLBACK.CATCH(6)), InlineKeyboardButton( text='\u2193', callback_data=Constants.CALLBACK.CATCH(7)), InlineKeyboardButton( text='\u2198', callback_data=Constants.CALLBACK.CATCH(8)) ]] reply_markup = InlineKeyboardMarkup(inline_keyboard=keys) sprites = { k: v for k, v in pokemon.sprites.items() if v is not None } sprite = pokemon.sprites[random.choice(list(sprites.keys()))] image = Pokemon.build_pokemon_catch_img( pokemon_sprite=sprite, direction=pokemon_direction) bio = BytesIO() bio.name = 'catch_img_' + str(player.chat_id) + '.png' image.save(bio, 'PNG') bio.seek(0) DBAccessor.insert_new_pokemon(pokemon) try: MessageHelper.delete_messages_by_type( bot, chat_id=player.chat_id, type=Constants.MESSAGE_TYPES.ENCOUNTER_MSG) msg = bot.send_photo(chat_id=player.chat_id, text='catch Pokemon!', photo=bio, reply_markup=reply_markup) player.messages_to_delete.append( Message.Message( _id=msg.message_id, _title=Constants.MESSAGE_TYPES.ENCOUNTER_MSG, _time_sent=now)) encounter = Encounter(pokemon_direction=pokemon_direction, pokemon=pokemon) query = { '$set': { 'last_encounter': now, 'messages_to_delete': [i.serialize_msg() for i in player.messages_to_delete], 'encounter': encounter.serialize() } } except telegram.error.Unauthorized as e: query = { '$set': { 'last_encounter': now, 'encounters': False }, '$unset': { 'encounter': 1 } } logging.error(e) DBAccessor.update_player(_id=player.chat_id, update=query)
def build_choose_from_team(bot, chat_id, duel_id): duel_id = int(duel_id) player = DBAccessor.get_player(chat_id) duel = DBAccessor.get_duel_by_id(int(duel_id)) friend_id = duel.participant_1.player_id if duel.participant_1.player_id != chat_id else duel.participant_2.player_id friend = DBAccessor.get_player(int(friend_id)) # If the Player should be informed about other participant's poke team # caption='' # for poke in friend.pokemon_team: # caption += '{} Lvl: {} HP: {}/{}\n'.format(poke.name, poke.level, poke.health, poke.max_health) if player is None: bot.send_message( chat_id=chat_id, text= 'I have not met you yet. Want to be a Pok\xe9mon trainer? Type /catch.' ) return elif len(duel.get_participant_by_id(chat_id).team ) is 0 or duel.get_participant_by_id(chat_id).team is None: bot.send_message( chat_id=chat_id, text= 'Your Pok\xe9mon team is empty. Choose candidates from your /bag.') return elif len(duel.get_participant_by_id(chat_id).team) > 6: bot.send_message( chat_id=chat_id, text= 'You somehow managed to add more than 6 Pok\xe9mon to your team. Outrageous! ' 'Please remove some :) (and blame the devs)') return pokemon_sprite_list, keys = [], [] for pokemon_id in duel.get_participant_by_id(chat_id).team: pokemon = DBAccessor.get_pokemon_by_id(pokemon_id) keys.append([ InlineKeyboardButton( text='{} Level:{} Health:{}/{}'.format(pokemon.name, pokemon.level, pokemon.health, pokemon.max_health), callback_data=Constants.CALLBACK.DUEL_ACTION_CHOSEN( event_id=duel.event_id, source_id=pokemon.poke_id)) ]) pokemon_sprite_list.append(pokemon.sprites['front']) MessageHelper.delete_messages_by_type( bot=bot, chat_id=chat_id, type=Constants.MESSAGE_TYPES.DUEL_CHOOSE_MSG) image = Pokemon.build_pokemon_bag_image( pokemon_sprite_list=pokemon_sprite_list, max_row_len=3) if image is not None: bio = BytesIO() bio.name = 'image_duel_choose_' + str(chat_id) + '.png' image.save(bio, 'PNG') bio.seek(0) reply_markup = InlineKeyboardMarkup(inline_keyboard=keys) msg = bot.send_photo( chat_id=chat_id, photo=bio, reply_markup=reply_markup, caption='Choose your champion in battle against {}!'.format( friend.username), parse_mode=ParseMode.MARKDOWN) else: msg = bot.send_message( chat_id=chat_id, text='Your team is empty, nominate some pokemon!') player.messages_to_delete.append( Message.Message(_id=msg.message_id, _title=Constants.MESSAGE_TYPES.DUEL_CHOOSE_MSG, _time_sent=time.time())) update = DBAccessor.get_update_query_player( messages_to_delete=player.messages_to_delete) DBAccessor.update_player(_id=player.chat_id, update=update)
def build_msg_duel_action_attack(bot, chat_id, duel_id): duel = DBAccessor.get_duel_by_id(int(duel_id)) duel.get_participant_by_id(chat_id).action = Duel.ActionAttack( duel_id=duel.event_id) duel.update_participant(chat_id) participant_player = duel.get_participant_by_id(chat_id) # participant = duel.get_counterpart_by_id(chat_id) poke1 = DBAccessor.get_pokemon_by_id(participant_player.pokemon) # poke2 = DBAccessor.get_pokemon_by_id(participant.pokemon) if participant_player.pokemon is None: bot.send_message( chat_id=participant_player.player_id, text= 'Your pokemon-champion is somehow not set! You have to choose again' ) raise AttributeError('Champion is None: Duel_id: {}'.format( duel.event_id)) elif poke1.moves is None or len(poke1.moves) is 0: bot.send_message( chat_id=participant_player.player_id, text='Your pokemon-champion has not enough attack moves!') raise AttributeError( 'Champion has no moves: Duel_id: {} Poke_id: {}'.format( duel.event_id, participant_player.pokemon)) keys = [] cross = emojize(":x:", use_aliases=True) for move in poke1.moves: # id # accuracy # power # pp # priority # target # type.name # names[find language.name == 'en'].name # move = Move.Move.get_move(m['url']) blocked = cross if move.target not in [ 'selected-pokemon', 'all-opponents' ] else '' keys.append([ InlineKeyboardButton( text='{}{} Acc:{} Pow:{} Prio:{}'.format( blocked, move.name, move.accuracy, move.power, move.priority), callback_data=Constants.CALLBACK.DUEL_ACTION_CHOSEN( event_id=duel.event_id, source_id=move.move_id)) ]) MessageHelper.delete_messages_by_type( bot=bot, chat_id=chat_id, type=Constants.MESSAGE_TYPES.DUEL_CHOOSE_MSG) MessageHelper.delete_messages_by_type( bot=bot, chat_id=chat_id, type=Constants.MESSAGE_TYPES.DUEL_STATUS_MSG) image = Pokemon.get_pokemon_portrait_image( pokemon_sprite=poke1.sprites['front']) if image is not None: bio = BytesIO() bio.name = 'image_duel_choose_attack_' + str(chat_id) + '.png' image.save(bio, 'PNG') bio.seek(0) reply_markup = InlineKeyboardMarkup(inline_keyboard=keys) msg = bot.send_photo(chat_id=chat_id, photo=bio, reply_markup=reply_markup, caption='Choose {}\'s attack'.format(poke1.name), parse_mode=ParseMode.MARKDOWN) else: msg = bot.send_message( chat_id=chat_id, text='Your team is empty, nominate some pokemon!') player = DBAccessor.get_player(int(chat_id)) player.messages_to_delete.append( Message.Message(_id=msg.message_id, _title=Constants.MESSAGE_TYPES.DUEL_CHOOSE_MSG, _time_sent=time.time())) update = DBAccessor.get_update_query_player( messages_to_delete=player.messages_to_delete) DBAccessor.update_player(_id=player.chat_id, update=update)
def build_msg_duel_active(bot, chat_id, duel_id): duel = DBAccessor.get_duel_by_id(int(duel_id)) if duel is not None and duel.participant_1.action is not None and duel.participant_2.action is not None and duel.participant_1.action.completed and duel.participant_2.action.completed: calc_round(bot, duel_id) if duel.get_participant_by_id(chat_id).team is not None: poke_player = [ DBAccessor.get_pokemon_by_id(i) for i in duel.get_participant_by_id(chat_id).team ] else: poke_player = None if duel.get_participant_by_id(chat_id).pokemon is not None: champion_player = DBAccessor.get_pokemon_by_id( duel.get_participant_by_id(chat_id).pokemon) else: champion_player = None if duel.get_counterpart_by_id(chat_id).pokemon is not None: champion_opponent = DBAccessor.get_pokemon_by_id( duel.get_counterpart_by_id(chat_id).pokemon) else: champion_opponent = None if duel.get_participant_by_id(chat_id).pokemon is not None: # Display Champion first for i, poke in enumerate(poke_player): if poke.poke_id == int( duel.get_participant_by_id(chat_id).pokemon): poke_player[0], poke_player[i] = poke_player[i], poke_player[0] break img = Pokemon.build_pokemon_duel_info_image(poke_player, champion_player, champion_opponent) keys = [] # keys = [[InlineKeyboardButton(text='Attack', callback_data=Constants.CALLBACK.DUEL_ACTION_ATTACK)], # [InlineKeyboardButton(text='Exchange Pokemon', callback_data=Constants.CALLBACK.DUEL_ACTION_POKEMON)], # [InlineKeyboardButton(text='Use Item', callback_data=Constants.CALLBACK.DUEL_ACTION_ITEM)]] caption = '' if duel.get_participant_by_id(chat_id).team is None: # TODO: Should this happen? Probably the team has to be chosen at this point already. keys.append([ InlineKeyboardButton( text='Choose Team', callback_data=Constants.CALLBACK.DUEL_TEAM_PAGE( duel.event_id, 0)) ]) elif duel.get_participant_by_id(chat_id).action is None: if duel.get_participant_by_id(chat_id).team is None or len( duel.get_participant_by_id( chat_id).team) < Constants.DUEL_MIN_POKEMON_PER_TEAM: keys.append( InlineKeyboardButton( text='Set up team', callback_data=Constants.CALLBACK.DUEL_START_CUSTOM( duel.event_id))) caption += 'You have to choose a team first!' else: if duel.get_participant_by_id(chat_id).pokemon is not None: keys.append([ InlineKeyboardButton( text='Attack', callback_data=Constants.CALLBACK.DUEL_ACTION_ATTACK( event_id=duel_id)) ]) keys.append([ InlineKeyboardButton( text='Nominate Champion', callback_data=Constants.CALLBACK.DUEL_ACTION_POKEMON( event_id=duel.event_id)) ]) keys.append([ InlineKeyboardButton( text='Use Item', callback_data=Constants.CALLBACK.DUEL_ACTION_ITEM( event_id=duel_id)) ]) else: keys.append([ InlineKeyboardButton(text='Remind {} to choose'.format( DBAccessor.get_player( duel.get_counterpart_by_id(chat_id).player_id).username), callback_data=Constants.CALLBACK.DUEL_NOTIFY( event_id=duel_id)) ]) if type(duel.get_participant_by_id( chat_id).action) == Duel.ActionAttack: caption += '\nYou chose to attack' if duel.get_participant_by_id( chat_id ).action.source is None and not duel.get_participant_by_id( chat_id).action.completed: keys.append([ InlineKeyboardButton( text='Choose Attack', callback_data=Constants.CALLBACK.DUEL_ACTION_ATTACK( event_id=duel.event_id)) ]) caption += ' but you have not chosen an attack yet!' elif type(duel.get_participant_by_id( chat_id).action) == Duel.ActionExchangePoke: if duel.get_participant_by_id( chat_id ).action.source is None and not duel.get_participant_by_id( chat_id).action.completed: keys.append([ InlineKeyboardButton( text='Nominate Champion', callback_data=Constants.CALLBACK.DUEL_ACTION_POKEMON( event_id=duel.event_id)) ]) caption += '\nYou chose to switch your champion but you have not chosen a champion yet!' else: caption += '\nYou chose to switch to {} as champion'.format( DBAccessor.get_pokemon_by_id( duel.get_participant_by_id( chat_id).action.source).name) elif type(duel.get_participant_by_id( chat_id).action) == Duel.ActionUseItem: caption += '\nYou chose to use an item' if duel.get_participant_by_id( chat_id ).action.source is None and not duel.get_participant_by_id( chat_id).action.completed: keys.append([ InlineKeyboardButton( text='Use Item', callback_data=Constants.CALLBACK.DUEL_ACTION_ITEM( event_id=duel.event_id)) ]) caption += ' but you have not chosen a champion yet!' keys.append([ InlineKeyboardButton(text='Surrender and abort duel', callback_data=Constants.CALLBACK.DUEL_ABORT( event_id=duel.event_id)) ]) reply_markup = InlineKeyboardMarkup(inline_keyboard=keys) player = DBAccessor.get_player(chat_id) MessageHelper.delete_messages_by_type( bot, player.chat_id, Constants.MESSAGE_TYPES.DUEL_STATUS_MSG) if img is not None: bio = BytesIO() bio.name = 'image_duel_info_' + str(chat_id) + '.png' img.save(bio, 'PNG') bio.seek(0) msg = bot.send_photo(chat_id=chat_id, photo=bio, caption='Current Status' + caption, reply_markup=reply_markup, parse_mode=ParseMode.MARKDOWN) else: msg = bot.send_message( chat_id=chat_id, text='Neither have you chosen your Pokemon team for ' 'this duel nor has your opponent nominated a champion.', reply_markup=reply_markup) player.messages_to_delete.append( Message.Message(_id=msg.message_id, _title=Constants.MESSAGE_TYPES.DUEL_STATUS_MSG, _time_sent=time.time())) query = DBAccessor.get_update_query_player( messages_to_delete=player.messages_to_delete) DBAccessor.update_player(_id=player.chat_id, update=query)