Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import discord
- import random
- import datetime
- import requests
- import aiohttp
- import json
- class MyBot(discord.Client):
- def __init__(self, quotes_file, api_keys, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.quotes = {}
- self.load_quotes(quotes_file)
- self.api_keys = api_keys
- async def on_ready(self):
- print(f'{self.user} has connected to Discord!')
- async def on_message(self, message):
- if message.author == self.user:
- return
- # Respond to the !hello command
- if message.content.startswith('!hello'):
- await message.channel.send('Hello!')
- # Flip a coin and respond to the !flip command
- if message.content.startswith('!flip'):
- flip = random.choice(['heads', 'tails'])
- await message.channel.send(flip)
- # Respond with the current time to the !time command
- if message.content.startswith('!time'):
- now = datetime.datetime.now()
- current_time = now.strftime("%H:%M:%S")
- await message.channel.send(f'The current time is {current_time}')
- # Respond with a random quote to the !quote command
- if message.content.startswith('!quote'):
- author, quote = self.get_random_quote()
- await message.channel.send(f'{quote} - {author}')
- # Get the weather for a specific location and respond to the !weather command
- if message.content.startswith('!weather'):
- location = message.content[8:]
- if not location:
- await message.channel.send('Please provide a location')
- return
- weather_data = self.get_weather_data(location)
- if not weather_data:
- await message.channel.send('Unable to get weather data for that location')
- return
- temperature = weather_data['main']['temp']
- weather_description = weather_data['weather'][0]['description']
- await message.channel.send(f'The weather in {location} is currently {weather_description} with a temperature of {temperature}°F')
- # Search for a GIF and respond to the !gif command
- if message.content.startswith('!gif'):
- query = message.content[4:]
- if not query:
- await message.channel.send('Please provide a search query')
- return
- gif_url = await self.get_gif_url(query)
- if not gif_url:
- await message.channel.send('Unable to find a GIF for that search query')
- return
- await message.channel.send(gif_url)
- def load_quotes(self, quotes_file):
- with open(quotes_file, 'r') as f:
- for line in f:
- author, quote = line.strip().split(' - ')
- self.quotes[author] = quote
- def get_random_quote(self):
- author = random.choice(list(self.quotes.keys()))
- quote = self.quotes[author]
- return author, quote
- def get_weather_data(self, location):
- api_key = self.api_keys['openweathermap']
- api_url = f'https://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}&units=imperial'
- r = requests.get(api_url)
- if r.status_code != 200:
- return None
- return r.json()
- async def get_gif_url(self, query):
- api_key = self.api_keys['giphy']
- api_url = f'https://api.giphy.com/v1/gifs/search?q={query}&api_key={api_key}'
- async with aiohttp.ClientSession() as session:
- async with session.get@client.command(name='joke', help='Tells a random joke')
- async def joke(ctx):
- response = requests.get('https://official-joke-api.appspot.com/random_joke')
- joke = response.json()
- await ctx.send(f"{joke['setup']} \n\n {joke['punchline']}")
- @client.command(name='wiki', help='Searches for a topic on Wikipedia')
- async def wiki(ctx, *, query):
- wikipedia.set_lang('en')
- try:
- summary = wikipedia.summary(query)
- await ctx.send(summary)
- except wikipedia.exceptions.DisambiguationError as e:
- options = "\n".join(e.options)
- await ctx.send(f"Please be more specific. Did you mean one of these: \n\n {options}")
- except wikipedia.exceptions.PageError as e:
- await ctx.send(f"Sorry, I couldn't find any results for {query}")
- @client.command(name='cat', help='Shows a random picture of a cat')
- async def cat(ctx):
- response = requests.get('https://api.thecatapi.com/v1/images/search')
- cat_url = response.json()[0]['url']
- await ctx.send(cat_url)
- @client.command(name='dog', help='Shows a random picture of a dog')
- async def dog(ctx):
- response = requests.get('https://dog.ceo/api/breeds/image/random')
- dog_url = response.json()['message']
- await ctx.send(dog_url)
- @client.command(name='translate', help='Translates a sentence to another language')
- async def translate(ctx, lang, *, text):
- translator = Translator(service_urls=['translate.google.com'])
- try:
- translation = translator.translate(text, dest=lang)
- await ctx.send(f"{text} ({translation.src}) -> {translation.text} ({translation.dest})")
- except ValueError as e:
- await ctx.send(f"Sorry, I couldn't translate that. Error message: {e}")
- @client.command(name='define', help='Defines a word')
- async def define(ctx, *, word):
- app_id = 'YOUR_OXFORD_DICTIONARY_APP_ID_HERE'
- app_key = 'YOUR_OXFORD_DICTIONARY_APP_KEY_HERE'
- language = 'en-gb'
- url = f"https://od-api.oxforddictionaries.com/api/v2/entries/{language}/{word.lower()}"
- headers = {'app_id': app_id, 'app_key': app_key}
- response = requests.get(url, headers=headers)
- if response.status_code == 404:
- await ctx.send(f"Sorry, I couldn't find a definition for {word}")
- else:
- data = response.json()
- results = []
- for result in data['results']:
- lexical_entries = result['lexicalEntries']
- for lexical_entry in lexical_entries:
- lexical_category = lexical_entry['lexicalCategory']['text']
- entries = lexical_entry['entries']
- for entry in entries:
- senses = entry['senses']
- for sense in senses:
- definition = sense['definitions'][0]
- results.append(f"{lexical_category}: {definition}")
- await ctx.send(f"**{word.capitalize()}**\n\n" + "\n\n".join(results))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement