Skip to content
Permalink
2f85e7af45
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
390 lines (334 sloc) 13.7 KB
######################################################
##### Asparuh's code for the chatbot project##########
######################################################
#Template used:
# https://www.devdungeon.com/content/make-discord-bot-python
# Discord.py documentation: https://discordpy.readthedocs.io/en/latest/api.html
# Help from stackoverflow
# https://www.youtube.com/watch?v=5yahh4tR0L0&list=PLW3GfRiBCHOiEkjvQj0uaUB1Q-RckYnj9
# Discord API - group.
# RapidAPI - https://rapidapi.com/
import discord #https://github.com/Rapptz/discord.py
from discord.ext import commands
import asyncio # Required to use some functions
from discord.utils import get
import json
from pprint import pprint
import requests
from urllib.request import urlopen
#Personal keys
rate_key = "095069ac1920332a79d881c9"
memes_key = 'rTZE4MlZ3ymshSfFBGKX7Iatc2app1NeCLejsne2jGvBBx2sXN'
flights_key = 'Um7Sn9CdQrmshlZwGdfNclEaBdPLp1fdlO5jsnspAUBm81IqvI'
TOKEN = 'NTA1MjkzMzE1NzkzNzQ3OTc4.DrRm1g.QTc1qMsuO0sX0mrQ6BQBEpKsMnc'
client= commands.Bot(command_prefix = '.')
SUPPORTED_CURRENCIES = {
"EUR": "European euro",
"USD": "US dollar",
"GBP": "Great Britain pounds",
"BRL": "Brazilian real"
}
base_currency = ""
target_currency_code = ""
CURRENCY_CODES = {
1: "EUR",
2: "USD",
3: "GBP",
4: "BRL"
}
# APIs
@client.command(pass_context=True)
async def exchangerate(ctx,):
url = ("https://v3.exchangerate-api.com/bulk/095069ac1920332a79d881c9/USD")
response = requests.get(url)
data = response.json()
print(data)
if __name__ == '__main__':
await client.say("Welcome to Currency Converter")
await client.say("Enter the amount you wish to convert: ")
message = await client.wait_for_message(author=ctx.message.author, channel=ctx.message.channel)
await client.say("Choose a base currency among our supported currencies:")
message1 = await client.wait_for_message(author=ctx.message.author, channel=ctx.message.channel)
for currencies in CURRENCY_CODES:
if message1 == currencies:
try:
url = "https://v3.exchangerate-api.com/bulk/095069ac1920332a79d881c9/USD"
url += rate_key
print(url)
url_rate = urlopen(url)
data = json.loads(url_rate.read())
except requests.exceptions.RequestException:
print('HTTP Request failed')
else:
await client.say("Invalid code")
await client.say("Choose a target currency among our supported currencies:")
target = await client.wait_for_message(author=ctx.message.author, channel=ctx.message.channel)
if target == CURRENCY_CODES:
try:
url = "https://v3.exchangerate-api.com/bulk/095069ac1920332a79d881c9/USD"
url += rate_key
print(url)
url_rate = urlopen(url)
exchangerate = json.loads(url_rate.read())
except requests.exceptions.RequestException:
print('HTTP Request failed')
else:
await client.say("Invalid code")
target_currency = CURRENCY_CODES
print("url_rate")
@client.command(pass_context=True)
async def cinema(ctx):
try:
movie = requests.get(
url="https://api.internationalshowtimes.com/v4/movies/",
params={
"countries": "GB",
},
headers={
"X-API-Key": "fghdqbFMn1QjoOJmBUm29Y7IA818QTU6",
},
)
print('Response HTTP Status Code: {status_code}'.format(
status_code=response.status_code))
print('Response HTTP Response Body: {content}'.format(
content=response.content))
except requests.exceptions.RequestException:
print('HTTP Request failed')
@client.command(pass_context=True)
async def memes(ctx):
memes = requests.get("https://ronreiter-meme-generator.p.rapidapi.com/meme?meme=Grumpy-Cat-Star-Wars&font_size=50&top=when+they+say&bottom=the+food+is+gone",
headers={
"X-Mashape-Key": "rTZE4MlZ3ymshSfFBGKX7Iatc2app1NeCLejsne2jGvBBx2sXN",
"X-Mashape-Host": "ronreiter-meme-generator.p.rapidapi.com"
}
)
try:
url_new = "https://ronreiter-meme-generator.p.rapidapi.com/meme=Grumpy-Cat-Star-Wars&font_size=50&top=when+they+say&bottom=the+food+is+gone"
url_new += memes_key
print(url_new)
url = urlopen(url_new)
meme_generator = json.loads(url.read())
except requests.exceptions.RequestException:
print('HTTP Request failed')
ctr = ["France","United+Kingdom","Portugal","Russia","Bulgaria"]
crc = "GBP"
locale ="en-US"
departure = ""
land = ""
outbound= ""
inbound= ""
cabinclass = ["economy","business","first"]
adults = 1
children = 0
infants = 0
response = requests.post("https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/pricing/v1.0",
headers={
"Content-Type": "application/x-www-form-urlencoded",
"X-Mashape-Key": "Um7Sn9CdQrmshlZwGdfNclEaBdPLp1fdlO5jsnspAUBm81IqvI",
"X-Mashape-Host": "skyscanner-skyscanner-flight-search-v1.p.rapidapi.com"},
data={
"country":ctr,
"currency":crc,
"locale":locale,
"originPlace":departure,
"destinationPlace":land,
"outboundDate":outbound,
"inboundDate":inbound,
"cabinClass": cabinclass,
"adults":adults,
"children":children,
"infants":infants,
"includeCarriers":"",
"excludeCarriers":"",
"groupPricing":"false"
}
)
#print(response.json())
ctrsearcher = requests.get("https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/autosuggest/v1.0/UK/GBP/en-EU/?query=France",
headers={
"X-Mashape-Key": "Um7Sn9CdQrmshlZwGdfNclEaBdPLp1fdlO5jsnspAUBm81IqvI",
"X-Mashape-Host": "skyscanner-skyscanner-flight-search-v1.p.rapidapi.com"
}
)
print(ctrsearcher.json())
user_message = ""
@client.command(pass_context=True)
async def flights(ctx):
msg = 'I see you want to travel.From where do you want to flight?'
await client.say(msg)
user_message = await client.wait_for_message(author=ctx.message.author, channel = ctx.message.channel)
if user_message != ctr:
question = "Sure! What country would you like me to check for?"
await client.say(question)
message = await client.wait_for_message(author=ctx.message.author, channel=ctx.message.channel)
message = message.content
for word in ctr:
if message == ctr:
try:
url = "https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/autosuggest/v1.0/UK/GBP/en-EU/?query=France"
url += flights_key
print(url)
url_add = urlopen(url)
flights = json.loads(url_add.read())
except requests.exceptions.RequestException:
print('HTTP Request failed')
else:
client.say("Sorry. I couldn't find it.")
# Functions
chat_restriction = ["die", "fuck", "cunt", "gay", "faggot"]
async def user_is_Bot(user):
author_roles = user.roles
has_right_role = False
for role in author_roles:
if role == discord.utils.get(user.server.roles):
has_right_role = True
return has_right_role
async def user_is_Admin(user):
author_roles = user.roles
has_right_role = False
for role in author_roles:
if role == discord.utils.get(user.server.roles):
has_right_role = True
return has_right_role
async def user_is_Gaybitch(user):
author_roles = user.roles
has_right_role = False
for role in author_roles:
if role == discord.utils.get(user.server.roles):
has_right_role = True
return has_right_role
##Used in the role fuction
@client.command(pass_context=True)
async def clear(ctx,amount=100):
channel = ctx.message.channel
messages = []
async for message in client.logs_from(channel, limit=int(amount) +1):
messages.append(message)
await client.delete_messages(messages)
await client.say('Message deleted')
# clear the wanted amount of messages between 1 and 100, I added (amount)+1, because it will not delete the last message, which will be the command.
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!hello'):
msg = 'Hello {0.author.mention}'.format(message)
await client.send_message(message.channel, msg)
if message.content.startswith('!how'):
msg = 'I am doing well,Thank you ! {0.author.mention}'.format(message)
await client.send_message(message.channel,msg)
if message.content.startswith('!Whatareyoudoing'):
msg = 'Nothing. I am stuck. {0.author.mention}'.format(message)
await client.send_message(message.channel,msg)
holder = message.content.split(" ")
for word in holder:
if word in chat_restriction:
await asyncio.sleep(3)
await client.delete_message(message)
await client.send_message(message.channel,"Hey! You are not allowed to say this!")
break
await client.process_commands(message) # need this so that the chat_restriction could be used in the fuction on_message
@client.command(pass_context=True)
async def commands(ctx):
author = ctx.message.author
embed = discord.Embed(
title = 'Chatbot commands',
description =
"Use **.** in front of the command"
"Example: .hello",
colour = discord.Colour.blue()
)
embed.add_field(name="Chat commands", value=
"``hello`` - Greet the Chatbot \n"
"``how`` - Checks how is the Chatbot \n"
"``Whatareyoudoing`` - Checks what is going to do tonight \n"
"``clear``- clear the amount of messages you want \n " # max 100(+1), wont delete messages older than 14days.
"``role`` - add or remove roles from the server \n"
"``checks`` - checks if the role exists \n"
"``kick`` - kicks members from the channel \n"
"``ban`` - bans members from the channel \n"
"``mute`` - mutes members from the channel \n"
"``unmute`` - unmutes members from the channel \n"
"``flights`` - gives all the airports from the selected country \n"
"``memes`` - randomly generators memes \n"
"``exchangerate`` - convert currency \n "
, inline=False)
embed.set_thumbnail(url=ctx.message.author.avatar_url)
embed.set_footer(text='Requested by ' + ctx.message.author.name + '.', icon_url=ctx.message.author.avatar_url)
# Synthesizes all the commands into an embed message so that they could be executed by the user.
await client.say(embed=embed)
avaialbe_roles = ["Admin", "Gaybitch", "Bot"]
@client.command(pass_context=True, name="role")
async def role(ctx, role: discord.Role=True, user: discord.user=True):
server = ctx.message.server
await user_is_Bot(ctx.message.author)
await user_is_Gaybitch(ctx.message.author)
await user_is_Admin(ctx.message.author)
role is False and user is True
await client.say("That role exists")
if role not in avaialbe_roles and user==True:
await client.add_roles(ctx.message.author, role)
await client.say("role has been added to roles.")
elif role not in avaialbe_roles and user==True:
await client.remove_roles(ctx.message.author, role)
await client.say("role has been removed.")
elif role not in server.roles:
await client.remove_roles(ctx.message.author, role)
await client.say("role has been removed from.")
else:
await client.say("Silly human, you do not have permission to use this command!")
@client.command(pass_context=True, name="check")
async def check(ctx, role: discord.Role=True):
server = ctx.message.server
current_roles = server.roles
if role in current_roles:
await client.say("That role exists")
return
else:
if role != server.roles:
await client.say("That role doesn't exist. Would you like to make it?")
reply = await client.wait_for_message(author=ctx.message.author, channel = ctx.message.channel)
if reply == "yes":
await client.edit_role(ctx.message.author, role)
await client.say("Role has been added to the server.")
elif reply == "no":
await client.say("No worries.")
@client.command(pass_context=True)
async def kick(ctx, member: discord.Member=None):
if not member:
await client.say("Please specify a member.")
return
else:
await client.say(f"{member.mention} got kicked.")
await client.kick(member)
@client.command(pass_context=True)
async def ban(ctx, member: discord.Member=None):
if not member:
await client.say("Please specify a member.")
return
else:
await client.say(f"{member.mention} got banned.")
await client.ban(member)
@client.command(pass_context=True)
async def mute(ctx, member: discord.Member=None):
if not member:
await client.say("Please specify a member.")
return
else:
await client.say(f"{member.mention} got muted.")
await client.mute(member)
@client.command(pass_context=True)
async def unmute(ctx, member: discord.Member=None):
if not member:
await client.say("Please specify a member.")
return
else:
await client.say(f"{member.mention} got unmuted.")
await client.unmute(member)
@client.event
async def on_ready():
print('I am ready and connected to discord')
print(client.user.name)
print(client.user.id)
print('------')
client.run(TOKEN)