SHARE
TWEET

first_try with a discord bot

DeaD_EyE Jul 31st, 2019 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from io import BytesIO
  2. from pathlib import Path
  3.  
  4. import discord
  5. from aiohttp import request
  6.  
  7.  
  8. class CommandHandler:
  9.     def __init__(self, bot):
  10.         self.bot = bot
  11.         # currently this reference is not used
  12.    
  13.     async def command(self, message):
  14.         if message.content.startswith('!wetter'):
  15.             await self.wetter(message)
  16.         if message.content.startswith('!links') and LINKS:
  17.             await message.channel.send(LINKS)
  18.    
  19.     async def wetter(self, message):
  20.         try:
  21.             _, city = message.content.split()
  22.         except ValueError:
  23.             return
  24.         url = f'https://wttr.in/{city.lower()}.png'
  25.         headers = {
  26.             'User-Agent': 'curl',
  27.             'Accept-Language': 'de',
  28.             }
  29.         async with request('GET', url, headers=headers) as rep:
  30.             if rep.status == 200:
  31.                 try:
  32.                     picture = await rep.read()
  33.                 except Exception:
  34.                     return
  35.                 discord_file = discord.File(BytesIO(picture), f'wetter_in_{city}.png')
  36.                 await message.channel.send(file=discord_file)
  37.  
  38.  
  39. class Bot(discord.Client):
  40.  
  41.     def __init__(self):
  42.         super().__init__()
  43.         self.command_handler = CommandHandler(self)
  44.  
  45.     async def on_message(self, message):
  46.         if message.author == self.user:
  47.             return
  48.         if message.content.startswith('!'):
  49.             await self.command_handler.command(message)
  50.  
  51.     async def on_ready(self):
  52.         print(f'Logged in as {self.user.name} with id {self.user.id}')
  53.  
  54.  
  55. if __name__ == '__main__':
  56.     token = Path('.discord_bot_token')
  57.     if not token.exists():
  58.         print(
  59.             f'{token} does not exist. Please create this file with your api token',
  60.             file=sys.stdout,
  61.             )
  62.         sys.exit(1)
  63.     links = Path('discord_bot_links.txt')
  64.     if links.exists():
  65.         LINKS = links.read_text()
  66.     else:
  67.         LINKS = None
  68.     token_str = token.read_text().strip()
  69.  
  70.     bot = Bot()
  71.     bot.run(token_str)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top