async def send_keyboard_input(self, string, press_enter_after_string=False): try: string = string.upper() logger.debug(string) # Special keys if string in ["UP", "DOWN", "LEFT", "RIGHT"]: key = getattr(uinput, "KEY_" + string) self.device.emit(key, 1) await asyncio.sleep(0.4) self.device.emit(key, 0) await asyncio.sleep(0.4) else: for i in string: logger.debug("Clicking {}".format(i)) key = getattr(uinput, "KEY_" + i) self.device.emit(key, 1) await asyncio.sleep(0.4) self.device.emit(key, 0) await asyncio.sleep(0.4) if press_enter_after_string: self.device.emit(uinput.KEY_ENTER, 1) await asyncio.sleep(0.4) self.device.emit(uinput.KEY_ENTER, 0) await asyncio.sleep(0.4) except Exception as e: logger.exception(e)
async def on_ready(self): # Changes the bot's status # activity = discord.Activity(name=f'{COMMAND_PREFIX}help in {len(self.bot.guilds)} servers', type=discord.ActivityType.listening) # await self.bot.change_presence(activity=activity) logger.debug("No of servers, bot is present in : {}".format( len(self.bot.guilds))) logger.debug('Bot is online!')
def producer(stats_queue, exe_file_path): process = subprocess.Popen(exe_file_path, stdout=subprocess.PIPE) for index, line in enumerate(iter(process.stdout.readline, b''), start=1): try: logger.debug(f"about to parse line number {index}") parsed_stat_line = json.loads(line) stats_queue.put(parsed_stat_line) except Exception: # All exceptions will be handled the same way, there is no need to catch each of them logger.error(f"Stat line number {index} is not a valid JSON, skipping")
async def sleep_until_time(trigger_time): # trigger_time needs be in hh:mm 24-hr format # ex: 12:30 hour = int(trigger_time.split(':')[0]) minute = int(trigger_time.split(':')[1]) t = datetime.datetime.today() future = datetime.datetime(t.year, t.month, t.day, hour, minute) if t.hour >= hour: future += datetime.timedelta(days=1) logger.debug("Sleeping for {} seconds...".format((future - t).seconds)) await asyncio.sleep((future - t).seconds)
async def daily_news(self): # Create DEBUG_FLAG_FILE file to avoid spamming group while testing/disable this cog if os.path.exists(DEBUG_FLAG_FILE): return for channel in self.channel_list: message_channel = self.bot.get_channel(channel) await message_channel.send("**Today's news **".format( date.today().strftime("%d/%m/%Y"))) logger.debug("PRE: {}".format(type(message_channel))) await get_news(message_channel)
async def post(self, ctx, *args): if args[0] == 'gb': channel = self.bot.get_channel(TEST2_CHANNEL_ID) message = ' '.join(args[1:]) elif args[0] == 'test': channel = self.bot.get_channel(TEST_CHANNEL_ID) message = ' '.join(args[1:]) else: channel = self.bot.get_channel(GENERAL_CHANNEL_ID) message = ' '.join(args) logger.debug("{} {}".format(len(args), message)) await channel.send(message)
async def on_message(self, message): logger.debug(message.content) if message.author == self.bot.user: return if self.game_mode: invalid_input_flag = False try: if message.content[:2].lower() == "up" and int( message.content[-1]) <= 5: for i in range(int(message.content[-1])): await self.keyboard.send_keyboard_input(GAMEBOY_UP) elif message.content[:4].lower() == "down" and int( message.content[-1]) <= 5: for i in range(int(message.content[-1])): await self.keyboard.send_keyboard_input(GAMEBOY_DOWN) elif message.content[:4].lower() == "left" and int( message.content[-1]) <= 5: for i in range(int(message.content[-1])): await self.keyboard.send_keyboard_input(GAMEBOY_LEFT) elif message.content[:5].lower() == "right" and int( message.content[-1]) <= 5: for i in range(int(message.content[-1])): await self.keyboard.send_keyboard_input(GAMEBOY_RIGHT) elif message.content.lower() == "a": await self.keyboard.send_keyboard_input(GAMEBOY_A) elif message.content.lower() == "b": await self.keyboard.send_keyboard_input(GAMEBOY_B) elif message.content.lower() == "l": await self.keyboard.send_keyboard_input(GAMEBOY_L) elif message.content.lower() == "r": await self.keyboard.send_keyboard_input(GAMEBOY_R) elif message.content.lower() == "select": await self.keyboard.send_keyboard_input(GAMEBOY_SELECT) elif message.content.lower() == "start": await self.keyboard.send_keyboard_input(GAMEBOY_START) else: logger.debug("Invalid game input!") invalid_input_flag = True await asyncio.sleep(0.4) # m +c - exit if not invalid_input_flag: take_screenshot("gb.png") await message.channel.send(file=discord.File('gb.png')) # game_channel = self.bot.get_channel(GAMEBOY_TEST_CHANNEL_ID) # await game_channel.send(file=discord.File('gb.png')) except ValueError as vale: logger.exception(vale) await message.channel.send("```Empty/Invalid entry```") except Exception as e: logger.exception(e)
async def get_advice(message_channel): logger.debug("advice") wait_message = await message_channel.send("Let me think...") try: session = aiohttp.ClientSession() async with session.get("https://api.adviceslip.com/advice") as resp: data = await resp.read() json_response = json.loads(data) await session.close() await wait_message.edit(content='*\"{}\"*'.format(json_response['slip']['advice'])) except Exception as e: logger.exception(e) await message_channel.send('Sorry can\'t think of anything')
async def get_insult(message_channel): logger.debug("advice") wait_message = await message_channel.send("Buckle up Butter cup...") try: session = aiohttp.ClientSession() async with session.get("https://insult.mattbas.org/api/insult.json") as resp: data = await resp.read() json_response = json.loads(data) await session.close() await wait_message.edit(content='*\"{}\"*'.format(json_response['insult'])) except Exception as e: logger.exception(e) await message_channel.send('No insult for you.')
async def get_fact(message_channel): logger.debug("advice") wait_message = await message_channel.send("One interesting fact coming right up...") try: session = aiohttp.ClientSession() async with session.get("https://useless-facts.sameerkumar.website/api") as resp: data = await resp.read() json_response = json.loads(data) await session.close() await wait_message.edit(content='*\"{}\"*'.format(json_response['data'])) except Exception as e: logger.exception(e) await message_channel.send('Sorry can\'t think of anything')
async def get_xkcd(message_channel): comic_number = random.randint(1, 2310) # comic number range TODO:get dynamically logger.debug(comic_number) try: session = aiohttp.ClientSession() url = "https://xkcd.com/{}/info.0.json".format(comic_number) async with session.get(url) as resp: data = await resp.read() json_response = json.loads(data) await session.close() embed = discord.Embed(title=json_response['title']) embed.set_image(url=json_response['img']) await embed_send(message_channel, embed) except Exception as e: logger.exception(e) await message_channel.send('No comic for you')
async def get_news(message_channel): logger.debug("news") # wait_message = await message_channel.send("Bringing you the latest BREAKING NEWS!") try: session = aiohttp.ClientSession() # read Bot Token from token file in keys folder with open('keys/news_api') as f: news_api_key = f.read() news_url = "https://newsapi.org/v2/top-headlines?sources=bbc-news&language=en&apiKey={}".format(news_api_key) async with session.get(news_url) as resp: data = await resp.read() json_response = json.loads(data) await session.close() embed_list = [] embed = "" news_message = "" for index in range(7): embed = discord.Embed(title=json_response['articles'][index]['title'], description=json_response['articles'][index]['description'], url=json_response['articles'][index]['url'], colour=discord.Color.darker_grey()) embed.set_thumbnail(url=json_response['articles'][index]['urlToImage']) embed_list.append(embed) news_message += "{}. {}\n".format(index + 1, json_response['articles'][index]['title']) # await wait_message.edit(content="```TOP HEADLINES:\n```".format(news_message)) if isinstance(message_channel, discord.ext.commands.context.Context) or isinstance(message_channel, discord.channel.TextChannel): # await message_channel.send(content="```TOP HEADLINES:\n{}```".format(news_message)) async with aiohttp.ClientSession() as session: webhook = Webhook.from_url( BRO_NEWS_WEBHOOK_URL, adapter=AsyncWebhookAdapter(session)) await webhook.send(content="```TOP HEADLINES```", embeds=embed_list) elif isinstance(message_channel, discord_slash.context.SlashContext): await message_channel.send(content="```TOP HEADLINES```", embeds=embed_list) else: logger.error("invalid ctx type: {}".format(type(message_channel))) await message_channel.send("ZZZzzzz") except Exception as e: logger.exception(e) await message_channel.send("No news for you.")
async def generate_quiz_question(self): category = "" question = "" options = "" correct_answer = "" try: session = aiohttp.ClientSession() url = 'https://opentdb.com/api.php?amount=1&category=9&difficulty={}&type=multiple'.format( self.QUIZ_DIFFICULTY) async with session.get(url) as resp: data = await resp.read() json_response = json.loads(data) await session.close() category = json_response['results'][0]['category'] question = json_response['results'][0]['question'] correct_answer = json_response['results'][0]['correct_answer'] incorrect_answers = json_response['results'][0][ 'incorrect_answers'] logger.debug("Category: {}".format(category)) logger.debug("Question: {}".format(question)) logger.debug("Answer: {}".format(correct_answer)) options = incorrect_answers.copy() options.append(correct_answer) random.shuffle(options) except Exception as e: logger.exception(e) return category, question, options, correct_answer
async def _twitchnotify(self, ctx, username=None): if username: client_id_path = os.path.join(ROOT_DIR, "keys/twitch_client_id") app_access_path = os.path.join(ROOT_DIR, "keys/twitch_app_access") with open(client_id_path) as f: client_id = f.read().strip() with open(app_access_path) as f: app_access_token = f.read().strip() headers = {'Client-ID': client_id, 'Authorization': 'Bearer ' + app_access_token, } twitch_user_api = "https://api.twitch.tv/helix/users?login={}".format(username) session = aiohttp.ClientSession() try: async with session.get(twitch_user_api, headers=headers) as resp: data = await resp.read() json_response = json.loads(data) logger.debug(json_response) if json_response['data']: path = Path(__file__).parent / "../../data/streamers.txt" with open(path, "a") as f: f.write(username+'\n') await ctx.send("Streamer added. Will notify you when **{}** goes live!".format(username)) else: await ctx.send("{} does not exists. Check streamer name and add again".format(username)) except Exception as e: logger.exception(e) await ctx.send("Sorry, could not add streamer. Try again later") finally: await session.close() else: await ctx.send("Provide a streamer name whose streams you want to be notified")
async def _tictactoe(self, ctx, difficulty="impossible"): if ctx.guild.id in games: await ctx.send("Game already in progress") else: games[ctx.guild.id] = TTT(board=[[".", ".", "."], [".", ".", "."], [".", ".", "."] ], computer="O", player="X", difficulty=difficulty) logger.debug("Starting TTT...") logger.debug(games) await ctx.send( "Starting game. Player plays 'X'. Enter input as x,y coordinate (valid range 0,0 to 2,2)\nExample: 1,2") logger.debug("Starting game") await ctx.send(games[ctx.guild.id].beautify_board()) self.game_mode = True logger.debug("Done")
async def runcmd(self, ctx, *args): logger.debug(args) if ctx.message.author.id == int(ADMIN_ID): try: result = subprocess.Popen(args, stdout=subprocess.PIPE) logger.debug(result.stdout) out = "" for line in result.stdout: out += line.decode('utf-8') logger.debug(out) await ctx.send("```{}```".format(out)) except Exception as e: logger.exception(e) else: await ctx.send('```Only my master can use this command.```')
async def send_keyboard_shortcut(self, list_of_keys): try: logger.debug(list_of_keys) for i in list_of_keys: logger.debug("Holding {}".format(i)) key = getattr(uinput, "KEY_" + i.upper()) self.device.emit(key, 1) await asyncio.sleep(0.4) for i in list_of_keys: logger.debug("Releasing {}".format(i)) key = getattr(uinput, "KEY_" + i) self.device.emit(key, 0) await asyncio.sleep(0.4) except Exception as e: logger.exception(e)
async def _quiz(self, ctx, arg=None): if not arg or arg == "noinstructions": self.QUIZ_MODE = True if arg != "noinstructions": await ctx.send( '```Instructions:\n' 'a. There will be a total of {} questions\n' 'b. Each question will have 4 options with 100 pts for correct answer\n' 'c. To answer, participants have to click on the appropriate reaction\n' 'd. Participants have {} seconds to answer each question\n' 'e. Selecting more than one choice will result in DISQUALIFICATION\n' 'f. Participant with the most points is the WINNER!\n```'. format(self.QUIZ_MAX_QUESTIONS, self.QUIZ_QUESTION_WAIT_TIME)) await asyncio.sleep(2) await ctx.send('```Game begins in 25 seconds...```') await asyncio.sleep(25) question_number = 1 participant_score = { } # dictionary which stores participant name and score while question_number <= self.QUIZ_MAX_QUESTIONS: if not self.QUIZ_MODE: # Stop quiz mode return async with ctx.typing(): category, question, options, answer = await self.generate_quiz_question( ) message = await ctx.send( html.unescape('\n**Question {}**\n' '**{}**\n' ':one: {}\n' ':two: {}\n' ':three: {}\n' ':four: {}\n'.format( question_number, question, options[0], options[1], options[2], options[3]))) emojis = [ "{}\N{COMBINING ENCLOSING KEYCAP}".format(num) for num in range(1, 5) ] # emoji code for 1,2,3,4 for emoji in emojis: await message.add_reaction(emoji) await asyncio.sleep(.75) participant_response = {} # dictionary to record user response # Give participants some time to react before moving on to next question time_at_start = datetime.datetime.today().timestamp() target_time = time_at_start + self.QUIZ_QUESTION_WAIT_TIME # wait for QUIZ_QUESTION_WAIT_TIME seconds for response logger.debug("time_at_start {}".format(time_at_start)) logger.debug("target_time {}".format(target_time)) while datetime.datetime.today().timestamp() < target_time: logger.debug("while now {}".format( datetime.datetime.today().timestamp())) try: reaction, user = await self.bot.wait_for( 'reaction_add', timeout=5, check=lambda reaction1, user1: str(reaction1.emoji ) in emojis) logger.debug("{} reacted with {}".format( user.display_name, reaction)) # TODO: remove older reaction if user changes option # message.remove_reaction(participant_response[user], user) participant_response.update( {user.display_name: emojis.index(reaction.emoji)}) except asyncio.TimeoutError: logger.debug("Timeout in Quiz") except Exception as e: logger.exception(e) await ctx.send("Correct answer was **{}**".format( html.unescape(answer))) for participant in participant_response: if participant == "Bro": continue if participant not in participant_score: participant_score.update({participant: 0}) if participant_response[participant] == options.index( answer): logger.debug( "Updating score for {}".format(participant)) participant_score.update({ participant: participant_score[participant] + 100 }) # show round score round_score = "" for participant in participant_score: round_score += "{}: {}\n".format( participant, participant_score[participant]) await ctx.send("```Score after Round {}\n{}```".format( question_number, round_score)) question_number += 1 await asyncio.sleep(3) logger.debug("quiz complete") winner = max(participant_score, key=participant_score.get) if participant_score[winner] != 0: await ctx.send( "{} is the WINNER. Congrats! :trophy: :first_place:". format(winner)) else: await ctx.send("No one scored any points. LOSERS!") elif arg.lower() == "stop": self.QUIZ_MODE = False await ctx.send('```Quiz mode stopped```') elif arg.lower() == "easy": self.QUIZ_DIFFICULTY = "easy" await ctx.send('```Quiz difficulty set to easy```') elif arg.lower() == "medium": self.QUIZ_DIFFICULTY = "medium" await ctx.send('```Quiz difficulty set to medium```') elif arg.lower() == "hard": self.QUIZ_DIFFICULTY = "hard" await ctx.send('```Quiz difficulty set to hard```') elif arg.isdigit(): if int(arg) > 30: await ctx.send( '```Quiz: max number of questions cannot be greater than 30```' ) else: self.QUIZ_MAX_QUESTIONS = int(arg) await ctx.send( '```Quiz: max number of questions set to {}```'.format( self.QUIZ_MAX_QUESTIONS)) else: # TODO: add option to change quiz config settings # number of questions # mode : easy, medium, hard # delay: ? pass
async def load_game_state(self): # m + f4 logger.debug("loading game state") await self.keyboard.send_keyboard_shortcut([GAMEBOY_HOTKEY, 'F4']) logger.debug("done")
async def save_game_state(self): # m + f2 logger.debug("saving game state") await self.keyboard.send_keyboard_shortcut([GAMEBOY_HOTKEY, 'F2']) logger.debug("done")
def __init__(self, bot): self.bot = bot self.live_status_dict = {} self.streamers = [] # Twitch user names logger.debug("starting self.twitch_notifier.start()") self.twitch_notifier.start()
async def twitch_notifier(self): await self.bot.wait_until_ready() client_id_path = os.path.join(ROOT_DIR, "keys/twitch_client_id") app_access_path = os.path.join(ROOT_DIR, "keys/twitch_app_access") with open(client_id_path) as f: client_id = f.read().strip() with open(app_access_path) as f: app_access_token = f.read().strip() url = "https://api.twitch.tv/helix/streams?user_login="******"https://api.twitch.tv/helix/games?id=" # Twitch get game api headers = {'Client-ID': client_id, 'Authorization': 'Bearer ' + app_access_token, } self.streamers = [] path = Path(__file__).parent / "../../data/streamers.txt" with open(path, "r") as f: for line in f: self.streamers.append(line.strip()) for player in self.streamers: if player not in self.live_status_dict.keys(): self.live_status_dict.update({player: TWITCH_NOT_STREAMING}) # Total 550-600 bytes of data fetched logger.debug(self.live_status_dict) channel = self.bot.get_channel(GENERAL_CHANNEL_ID) # channel to which notification should be sent session = aiohttp.ClientSession() try: for streamer in self.streamers: twitch_url = url + streamer async with session.get(twitch_url, headers=headers) as resp: data = await resp.read() json_response = json.loads(data) logger.debug(json_response) # if data not empty, user is streaming if json_response['data']: if self.live_status_dict[streamer] == TWITCH_NOT_STREAMING: try: game_id = json_response['data'][0]['game_id'] if game_id: # get info on game the user is playing async with session.get(games_url + game_id, headers=headers) as resp: game_data = await resp.read() game_response = json.loads(game_data) logger.debug(game_response) # size: 140 bytes logger.debug("https://www.twitch.tv/{}".format(json_response['data'][0]['user_name'])) await channel.send( "**{} is live on Twitch playing {}!**\nhttps://www.twitch.tv/{}".format(json_response['data'][0]['user_name'], game_response['data'][0]['name'], json_response['data'][0]['user_name'])) else: await channel.send( "**{} is live on Twitch!**\nhttps://www.twitch.tv/{}".format( json_response['data'][0]['user_name'], json_response['data'][0]['user_name'])) self.live_status_dict[streamer] = TWITCH_STARTED_STREAMING except Exception as e: logger.exception(e) else: logger.debug("{} is still live. not sending".format(streamer)) self.live_status_dict[streamer] = TWITCH_STILL_STREAMING else: logger.debug("{} is not live".format(streamer)) if self.live_status_dict[streamer] == TWITCH_STARTED_STREAMING or self.live_status_dict[ streamer] == TWITCH_STILL_STREAMING: await channel.send("{}\'s stream has ended.".format(streamer)) self.live_status_dict[streamer] = TWITCH_NOT_STREAMING await asyncio.sleep(2) except Exception as e: logger.exception(e) finally: await session.close()
async def on_message(self, message): # logger.debug(message.content) if message.author == self.bot.user: return try: if not self.game_mode: # to process messages only if game has started return user_input = message.content.split(',') # validations if len(user_input) > 2: return if int(user_input[0]) < 0 or int(user_input[0]) > 2 or int(user_input[1]) < 0 or int(user_input[1]) > 2: return if self.bot_thinking: await message.channel.send("Slow down Bro. Try again...") return game = games[message.guild.id] # adding check to see if position is already filled if game.board[int(user_input[0])][int(user_input[1])] == ".": self.bot_thinking = True # added flag to handle user input spam while bot is executing api game.board[int(user_input[0])][int(user_input[1])] = game.player await message.channel.send(game.beautify_board()) if game.hasWon(game.board): await message.channel.send("Congratulations! Player has won :trophy: :first_place:") del games[message.guild.id] # delete game instance self.bot_thinking = False logger.debug(games) return elif game.hasWon(game.board) is None: await message.channel.send("Match drawn :handshake:") del games[message.guild.id] # delete game instance self.bot_thinking = False logger.debug(games) return await message.channel.send("Thinking...") # await asyncio.sleep(0.25) logger.debug("DIFFICULTY:") logger.debug(game.difficulty) post_data = { "positions": game.board, "player": "X", "difficulty": game.difficulty } async with aiohttp.ClientSession() as session: async with session.post(url, json=post_data) as resp: user_input = await resp.json() if user_input["move"]: game.board[int(user_input["move"][0])][int(user_input["move"][1])] = game.computer await message.channel.send(game.beautify_board()) self.bot_thinking = False if game.hasWon(game.board): await message.channel.send("GrandMaster Bro wins! :robot:") del games[message.guild.id] # delete game instance logger.debug(games) elif game.hasWon(game.board) is None: await message.channel.send("Match drawn :handshake:") del games[message.guild.id] # delete game instance logger.debug(games) else: await message.channel.send("Position already filled. Try some other coordinate...") except ValueError as vale: logger.exception(vale) except Exception as e: logger.exception(e) self.bot_thinking = False
async def change_status(self): logger.debug("Changing status...") await self.bot.change_presence(activity=next(self.status))
async def game(self, ctx, arg=None): if not arg: await ctx.send('```Usage:\n' '{}game on : to activate game mode\n' '{}game off : to deactivate game mode\n' '{}game savestate : to save game state\n' '{}game loadstate : to load game state\n```'.format( COMMAND_PREFIX, COMMAND_PREFIX, COMMAND_PREFIX, COMMAND_PREFIX)) return if arg.lower() == "on": if not self.game_mode: async with ctx.typing(): await ctx.send( "Starting game. Please wait. This might take upto a minute" ) self.game_mode = True logger.debug("Starting game") await self.keyboard.send_keyboard_input( "emulationstation", True) logger.debug("Starting game engine...") await asyncio.sleep(30) logger.debug("Done") await asyncio.sleep(1) logger.debug("Starting GBA...") await self.keyboard.send_keyboard_input(GAMEBOY_A) logger.debug("Done") await asyncio.sleep(1) logger.debug("Starting Pokemon...") await self.keyboard.send_keyboard_input(GAMEBOY_A) await asyncio.sleep(25) logger.debug("Done") await self.load_game_state() await asyncio.sleep(1) logger.debug("Taking screenshot...") take_screenshot("gb.png") logger.debug("Game ready to play") await ctx.send("Game ready to play") await asyncio.sleep(1) await ctx.send('```GAME MODE ACTIVATED!```') await ctx.send( '```Available Keys:\n' ' up <number>: to move up\n' ' down <number>: to move down\n' ' left <number>: to move left\n' ' right <number>: to move right\n' ' a : to press A\n' ' b : to press B\n' ' select: to press Select\n' ' start: to press Start\n```'.format(COMMAND_PREFIX)) # game_channel = self.bot.get_channel(GAMEBOY_TEST_CHANNEL_ID) await ctx.send(file=discord.File('gb.png')) logger.debug("Done") else: await ctx.send("Game is already running") elif arg.lower() == "off": if self.game_mode: async with ctx.typing(): await ctx.send('Stopping game safely. Please wait.') await self.save_game_state() logger.debug("Stopping game") await self.keyboard.send_keyboard_shortcut( [GAMEBOY_HOTKEY, GAMEBOY_START]) logger.debug("Done") await asyncio.sleep(10) logger.debug("Stopping Retropie") ''' send_keyboard_input("v") # Menu await asyncio.sleep(1) send_keyboard_input(GAMEBOY_UP) # up await asyncio.sleep(1) send_keyboard_input("v") # QUIT await asyncio.sleep(1) send_keyboard_input(GAMEBOY_UP) # QUIT emu await asyncio.sleep(1) send_keyboard_input("v") # await asyncio.sleep(1) logger.debug("Done") await asyncio.sleep(10) ''' logger.debug("Killing retroarch") os.system("sudo kill $(pidof retroarch)") logger.debug("Done") await asyncio.sleep(10) logger.debug("Killing emulationstation") os.system("sudo kill $(pidof emulationstation)") logger.debug("Done") await asyncio.sleep(10) # logger.debug("Taking screenshot...") # take_screenshot("gb.png") self.game_mode = False logger.debug("Done") await ctx.send('```GAME MODE DEACTIVATED, BYE!```') else: await ctx.send("Game is not running.") elif arg.lower() == "loadstate": if self.game_mode: await self.load_game_state() await ctx.send('Loaded game from previously saved state') take_screenshot("gb.png") await ctx.send(file=discord.File('gb.png')) else: await ctx.send('Game is not running. ') elif arg.lower() == "savestate": if self.game_mode: await self.save_game_state() await ctx.send('Game saved!') take_screenshot("gb.png") await ctx.send(file=discord.File('gb.png')) else: await ctx.send('Game is not running. ') else: await ctx.send('```Invalid entry```') await ctx.send('```Usage:\n' '{}game on : to activate game mode\n' '{}game off : to deactivate game mode\n' '{}game savestate : to save game state\n' '{}game loadstate : to load game state\n```'.format( COMMAND_PREFIX, COMMAND_PREFIX, COMMAND_PREFIX, COMMAND_PREFIX))
async def _stats(self, ctx, user: discord.Member): try: wait_message = await ctx.send( "Processing... Please wait. This might take sometime") embed = "" if not user: try: logger.debug("no user given...") embed = discord.Embed( title="Stats", description="Showing random stats for this server", colour=discord.Color.blue()) embed.set_footer(text="Hope that was helpful, bye!") embed.set_author(name="Bro Bot", icon_url=self.bot.user.avatar_url) embed.set_thumbnail(url=ctx.guild.icon_url) server = ctx.message.author.guild server_name = server.name server_owner = server.owner.mention server_create_date = server.created_at.__format__( '%d/%B/%Y') server_member_count = server.member_count logger.debug("*****************************") logger.debug( "Server name: {}\nserver owner: {}\nserver created at: {}\nTotal number of members: {}" .format(server_name, server_owner, server_create_date, server_member_count)) embed.add_field(name="Server Name", value=server_name, inline=False) embed.add_field(name="Server Owner", value=server_owner, inline=True) embed.add_field(name="Server Create Date", value=server_create_date, inline=True) embed.add_field(name="Total Members", value=server_member_count, inline=True) # channel = bot.get_channel(GENERAL_CHANNEL_ID) # messages = await channel.history(limit=None).flatten() messages = await ctx.channel.history(limit=None).flatten() logger.debug("Total messages: {}".format(len(messages))) embed.add_field(name="Total messages in this channel", value=str(len(messages)), inline=False) authors_count = Counter() word_count = Counter() message_list = list() bro_in_message_count = 0 # pre processing full_stopwords = stopwords.words('english') full_stopwords.extend(ADDITIONAL_STOPWORDS) for message in messages: if "bro" in str(message.content).lower(): bro_in_message_count += 1 authors_count.update({message.author.name: 1}) word_list = message.content.split() filtered_words = [ word for word in word_list if word not in full_stopwords ] message_list += filtered_words word_count.update(message_list) authors_count.pop('notDiegoDelavega', None) # removing test users from stat top = authors_count.most_common(1) logger.debug( "Most talkative bro: {} talked {} times".format( top[0][0], top[0][1])) value = str(top[0][0] if ctx.guild.get_member_named( top[0][0]) is None else ctx.guild.get_member_named( top[0][0]).mention) + " (" + str( top[0][1]) + " messages)" logger.debug(value) embed.add_field(name="Most Talkative Bro", value=value, inline=False) low = min(authors_count, key=authors_count.get) logger.debug( "Least talkative bro: {} talked {} time(s)".format( low, authors_count[low])) value = str( low if ctx.guild.get_member_named(low) is None else ctx .guild.get_member_named(low).mention) + " (" + str( authors_count[low]) + " messages)" embed.add_field(name="Least Talkative Bro", value=value, inline=True) top_authors = "" if len(authors_count) >= 5: logger.debug("Top 5 talkative Bros") for author, message_count in authors_count.most_common( 5): logger.debug("{}: {} times".format( author, message_count)) top_authors += str( author if ctx.guild.get_member_named(author) is None else ctx.guild.get_member_named(author).mention ) + " (" + str(message_count) + " messages) \n" embed.add_field(name="Top 5 Talkative Bros", value=top_authors, inline=False) top_string = "" if len(word_count) >= 5: logger.debug("Top five words used here are:") for word, count in word_count.most_common(5): logger.debug("{}: {} times".format(word, count)) top_string += str(word) + " (" + str( count) + " times) \n" embed.add_field(name="Top 5 words used here", value=top_string, inline=False) logger.debug("Bro was mentioned {} times!".format( bro_in_message_count)) embed.add_field(name="Bro Count", value=str(bro_in_message_count), inline=False) logger.debug("*****************************") except Exception as e: logger.exception(e) else: embed = discord.Embed( title="Stats", description="Showing random stats for user", colour=discord.Color.purple()) embed.set_footer(text="Hope that was helpful, bye!") embed.set_author(name="Bro Bot", icon_url=self.bot.user.avatar_url) embed.set_thumbnail(url=user.avatar_url) logger.debug("*****************************") logger.debug("user name: {}".format(user.mention)) logger.debug("user join date: {}".format( user.joined_at.__format__('%d/%B/%Y @%H:%M:%S'))) embed.add_field(name="User Name", value=user.mention, inline=False) embed.add_field(name="User Join Date", value=user.joined_at.__format__('%d/%B/%Y'), inline=False) messages = await ctx.channel.history(limit=None).flatten() message_list = list() word_count = Counter() for message in messages: if user == message.author: message_list += str(message.content).split() word_count.update(message_list) top_string = "" if len(word_count) >= 5: logger.debug("Top five words used by {}:".format( user.display_name)) top_name = "Top 5 words used by {} in this server:".format( user.display_name) for word, count in word_count.most_common(5): logger.debug("{}: {} times".format(word, count)) top_string += str(word) + " (" + str( count) + " times) \n" embed.add_field(name=top_name, value=top_string, inline=False) logger.debug("*****************************") await wait_message.delete() await embed_send(ctx, embed) # await wait_message.edit(content='', embed=embed) # await ctx.send(embed=embed) except Exception as e: logger.exception(e)
def take_screenshot(filename="test.png"): logger.debug("taking screenshot") os.system("raspi2png -p {}".format(filename)) return 0
async def on_message(self, message): # logger.debug(message.content) if message.author == self.bot.user: return full_message = message.content.lower( ) # has full message in lower case full_message_list = full_message.split() # message is split on spaces if 'bro' in full_message_list: logger.debug("Sending Bro message") await message.channel.send("Bro", tts=False) if 'hello' in full_message_list or 'hi' in full_message_list: logger.debug("Sending hello message") await message.channel.send("Hello {} bro".format( message.author.mention)) if 'bye' in full_message_list: logger.debug("Sending bye message") await message.channel.send("Bye Bye {} bro".format( message.author.mention)) await message.author.send('👋') if 'good morning' in full_message or 'gm' in full_message_list: logger.debug("Sending gm message") await message.channel.send("Good morning bros") if 'good night' in full_message or 'gn' in full_message_list: logger.debug("Sending gn message") await message.channel.send("Good night bros") if 'good game' in full_message or 'gg' in full_message_list: logger.debug("Sending gn message") await message.channel.send("gg bros") if "i\'m online" in full_message or "im online" in full_message: logger.debug("Sending online message") await message.channel.send("I'm online too bro") # if "tictactoe" in full_message: # await message.channel.send("Kai is trying to build this. Coming soon..\n P.S : I hope so - Pavan") # await ttt.start_game(message) ''' if 'stream' in full_message: # or 'play' in full_message and '-play' not in full_message: logger.debug("Sending stream/play message") await message.channel.send("***STREAM STREAM STREAM!***") await message.channel.send(random.choice(WAR_CRY_LIST), tts=True) ''' '''
'cogs.background.daily_news', 'cogs.background.f1_calendar', #'cogs.general.music', 'cogs.background.status_changer', 'cogs.background.sleep_remainder', 'cogs.games.tictactoe' ] intents = discord.Intents.all() bot = commands.Bot(command_prefix=COMMAND_PREFIX, description='The Bro Bot', intents=intents) slash = SlashCommand(bot, sync_commands=True) if __name__ == '__main__': logger.debug("Bro Bot Startup...") # load initial cogs for cog in BOT_STARTUP_COGS_LIST: try: logger.debug("Loading cog : {}".format(cog)) bot.load_extension(cog) except Exception as e: logger.exception("Failed to load extension {}. ERROR: {}".format( cog, e)) # read Bot Token from token file in keys folder with open('keys/token') as f: TOKEN = f.read() bot.run(TOKEN, bot=True, reconnect=True)
async def _intro(self, ctx): logger.debug("Sending intro message") embed = discord.Embed(title="Say Bro and I\'ll bro you back") embed.set_image( url="https://media.giphy.com/media/l0K45p4XQTVmyClMs/giphy.gif") await embed_send(ctx, embed)