Advertisement
YourMain12

Discord Bot v1.0.4

Jan 8th, 2023 (edited)
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.49 KB | None | 0 0
  1. import discord
  2. import random
  3. import datetime
  4. import requests
  5. import aiohttp
  6. import json
  7.  
  8. class MyBot(discord.Client):
  9.     def __init__(self, quotes_file, api_keys, *args, **kwargs):
  10.         super().__init__(*args, **kwargs)
  11.         self.quotes = {}
  12.         self.load_quotes(quotes_file)
  13.         self.api_keys = api_keys
  14.  
  15.     async def on_ready(self):
  16.         print(f'{self.user} has connected to Discord!')
  17.  
  18.     async def on_message(self, message):
  19.         if message.author == self.user:
  20.             return
  21.  
  22.         # Respond to the !hello command
  23.         if message.content.startswith('!hello'):
  24.             await message.channel.send('Hello!')
  25.  
  26.         # Flip a coin and respond to the !flip command
  27.         if message.content.startswith('!flip'):
  28.             flip = random.choice(['heads', 'tails'])
  29.             await message.channel.send(flip)
  30.  
  31.         # Respond with the current time to the !time command
  32.         if message.content.startswith('!time'):
  33.             now = datetime.datetime.now()
  34.             current_time = now.strftime("%H:%M:%S")
  35.             await message.channel.send(f'The current time is {current_time}')
  36.  
  37.         # Respond with a random quote to the !quote command
  38.         if message.content.startswith('!quote'):
  39.             author, quote = self.get_random_quote()
  40.             await message.channel.send(f'{quote} - {author}')
  41.  
  42.         # Get the weather for a specific location and respond to the !weather command
  43.         if message.content.startswith('!weather'):
  44.             location = message.content[8:]
  45.             if not location:
  46.                 await message.channel.send('Please provide a location')
  47.                 return
  48.             weather_data = self.get_weather_data(location)
  49.             if not weather_data:
  50.                 await message.channel.send('Unable to get weather data for that location')
  51.                 return
  52.             temperature = weather_data['main']['temp']
  53.             weather_description = weather_data['weather'][0]['description']
  54.             await message.channel.send(f'The weather in {location} is currently {weather_description} with a temperature of {temperature}°F')
  55.  
  56.         # Search for a GIF and respond to the !gif command
  57.         if message.content.startswith('!gif'):
  58.             query = message.content[4:]
  59.             if not query:
  60.                 await message.channel.send('Please provide a search query')
  61.                 return
  62.             gif_url = await self.get_gif_url(query)
  63.             if not gif_url:
  64.                 await message.channel.send('Unable to find a GIF for that search query')
  65.                 return
  66.             await message.channel.send(gif_url)
  67.  
  68.     def load_quotes(self, quotes_file):
  69.         with open(quotes_file, 'r') as f:
  70.             for line in f:
  71.                 author, quote = line.strip().split(' - ')
  72.                 self.quotes[author] = quote
  73.  
  74.     def get_random_quote(self):
  75.         author = random.choice(list(self.quotes.keys()))
  76.         quote = self.quotes[author]
  77.         return author, quote
  78.  
  79.     def get_weather_data(self, location):
  80.         api_key = self.api_keys['openweathermap']
  81.         api_url = f'https://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}&units=imperial'
  82.         r = requests.get(api_url)
  83.         if r.status_code != 200:
  84.             return None
  85.         return r.json()
  86.  
  87.     async def get_gif_url(self, query):
  88.         api_key = self.api_keys['giphy']
  89.         api_url = f'https://api.giphy.com/v1/gifs/search?q={query}&api_key={api_key}'
  90.         async with aiohttp.ClientSession() as session:
  91.             async with session.get@client.command(name='joke', help='Tells a random joke')
  92. async def joke(ctx):
  93.     response = requests.get('https://official-joke-api.appspot.com/random_joke')
  94.     joke = response.json()
  95.     await ctx.send(f"{joke['setup']} \n\n {joke['punchline']}")
  96.  
  97. @client.command(name='wiki', help='Searches for a topic on Wikipedia')
  98. async def wiki(ctx, *, query):
  99.     wikipedia.set_lang('en')
  100.     try:
  101.         summary = wikipedia.summary(query)
  102.         await ctx.send(summary)
  103.     except wikipedia.exceptions.DisambiguationError as e:
  104.         options = "\n".join(e.options)
  105.         await ctx.send(f"Please be more specific. Did you mean one of these: \n\n {options}")
  106.     except wikipedia.exceptions.PageError as e:
  107.         await ctx.send(f"Sorry, I couldn't find any results for {query}")
  108.  
  109. @client.command(name='cat', help='Shows a random picture of a cat')
  110. async def cat(ctx):
  111.     response = requests.get('https://api.thecatapi.com/v1/images/search')
  112.     cat_url = response.json()[0]['url']
  113.     await ctx.send(cat_url)
  114.  
  115. @client.command(name='dog', help='Shows a random picture of a dog')
  116. async def dog(ctx):
  117.     response = requests.get('https://dog.ceo/api/breeds/image/random')
  118.     dog_url = response.json()['message']
  119.     await ctx.send(dog_url)
  120.  
  121. @client.command(name='translate', help='Translates a sentence to another language')
  122. async def translate(ctx, lang, *, text):
  123.     translator = Translator(service_urls=['translate.google.com'])
  124.     try:
  125.         translation = translator.translate(text, dest=lang)
  126.         await ctx.send(f"{text} ({translation.src}) -> {translation.text} ({translation.dest})")
  127.     except ValueError as e:
  128.         await ctx.send(f"Sorry, I couldn't translate that. Error message: {e}")
  129.  
  130. @client.command(name='define', help='Defines a word')
  131. async def define(ctx, *, word):
  132.     app_id = 'YOUR_OXFORD_DICTIONARY_APP_ID_HERE'
  133.     app_key = 'YOUR_OXFORD_DICTIONARY_APP_KEY_HERE'
  134.     language = 'en-gb'
  135.     url = f"https://od-api.oxforddictionaries.com/api/v2/entries/{language}/{word.lower()}"
  136.     headers = {'app_id': app_id, 'app_key': app_key}
  137.     response = requests.get(url, headers=headers)
  138.     if response.status_code == 404:
  139.         await ctx.send(f"Sorry, I couldn't find a definition for {word}")
  140.     else:
  141.         data = response.json()
  142.         results = []
  143.         for result in data['results']:
  144.             lexical_entries = result['lexicalEntries']
  145.             for lexical_entry in lexical_entries:
  146.                 lexical_category = lexical_entry['lexicalCategory']['text']
  147.                 entries = lexical_entry['entries']
  148.                 for entry in entries:
  149.                     senses = entry['senses']
  150.                     for sense in senses:
  151.                         definition = sense['definitions'][0]
  152.                         results.append(f"{lexical_category}: {definition}")
  153.         await ctx.send(f"**{word.capitalize()}**\n\n" + "\n\n".join(results))
  154.  
Tags: python
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement