Last active
September 19, 2018 18:15
-
-
Save Bert-Macklin/08cb5f01145c5871fb1c2c2aaad16aba to your computer and use it in GitHub Desktop.
Making a Discord Bot in Python 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# bot.py | |
import discord | |
# command handler class | |
class CommandHandler: | |
# constructor | |
def __init__(self, client): | |
self.client = client | |
self.commands = [] | |
def add_command(self, command): | |
self.commands.append(command) | |
def command_handler(self, message): | |
for command in self.commands: | |
if message.content.startswith(command['trigger']): | |
args = message.content.split(' ') | |
if args[0] == command['trigger']: | |
args.pop(0) | |
if command['args_num'] == 0: | |
return self.client.send_message(message.channel,str(command['function'](message, self.client, args))) | |
break | |
else: | |
if len(args) >= command['args_num']: | |
return self.client.send_message(message.channel,str(command['function'](message, self.client, args))) | |
break | |
else: | |
return self.client.send_message(message.channel, 'command "{}" requires {} argument(s) "{}"'.format(command['trigger'], command['args_num'], ', '.join(command['args_name']))) | |
break | |
else: | |
break | |
# create discord client | |
client = discord.Client() | |
token = 'NDI3MjIyOTExMjg0NDEyNDQ2.DZhfMA.h3sx9iq6vO_ROYtlxHHTSZJz0xs' | |
# create the CommandHandler object and pass it the client | |
ch = CommandHandler(client) | |
# command's functions | |
## start hello command | |
def hello_function(message, client, args): | |
try: | |
return 'Hello {}, Argument One: {}'.format(message.author, args[0]) | |
except Exception as e: | |
return e | |
ch.add_command({ | |
'trigger': '!hello', | |
'function': hello_function, | |
'args_num': 1, | |
'args_name': ['string'], | |
'description': 'Will respond hello to the caller' | |
}) | |
## end hello command | |
# bot is ready | |
@client.event | |
async def on_ready(): | |
try: | |
print(client.user.name) | |
print(client.user.id) | |
except Exception as e: | |
print(e) | |
# on new message | |
@client.event | |
async def on_message(message): | |
# if the message is from the bot itself ignore it | |
if message.author == client.user: | |
pass | |
else: | |
# try to evaluate with the command handler | |
try: | |
await ch.command_handler(message) | |
# message doesn't contain a command trigger | |
except TypeError as e: | |
pass | |
# generic python error | |
except Exception as e: | |
print(e) | |
# start bot | |
client.run(token) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment