Hey there, fellow dev! Ready to dive into the world of Discord bots? You're in for a treat. We'll be using discord.py, a powerful package that makes interacting with Discord's API a breeze. Assuming you've got your Python chops and a Discord account ready to go, let's jump right in!
First things first, let's get our tools in order:
pip install discord.py
Now, head over to the Discord Developer Portal, create a new application, and add a bot to it. Jot down that bot token – you'll need it soon!
Time to write some code! Let's start with the basics:
import discord from discord.ext import commands bot = commands.Bot(command_prefix='!') @bot.event async def on_ready(): print(f'{bot.user} has connected to Discord!') bot.run('YOUR_BOT_TOKEN_HERE')
This sets up your bot with a command prefix of '!' and prints a message when it's ready to roll.
Let's add some meat to our bot's bones:
@bot.command() async def ping(ctx): await ctx.send('Pong!') @bot.event async def on_message(message): if message.author == bot.user: return if 'hello' in message.content.lower(): await message.channel.send('Hey there!') await bot.process_commands(message)
Now your bot can respond to a !ping command and say hello when greeted. Pretty cool, right?
Ready to level up? Let's add some fancier features:
@bot.event async def on_reaction_add(reaction, user): if str(reaction.emoji) == '👍': await reaction.message.channel.send(f'{user} liked that!') @bot.command() async def info(ctx): embed = discord.Embed(title="Bot Info", description="I'm a cool bot!", color=0x00ff00) embed.add_field(name="Creator", value="Your Name", inline=False) await ctx.send(embed=embed) @bot.command() @commands.has_permissions(manage_roles=True) async def giverole(ctx, user: discord.Member, role: discord.Role): await user.add_roles(role) await ctx.send(f'Gave {role.name} to {user.name}')
These snippets handle reactions, send fancy embeds, and manage roles. Neat, huh?
Now that your bot's got some skills, it's time to set it free! You've got a few hosting options:
Whichever you choose, make sure it can run 24/7 for maximum bot availability.
As your bot grows, keep these tips in mind:
And there you have it! You've just built a Discord bot from scratch. Pretty awesome, right? Remember, this is just the tip of the iceberg. The Discord API and discord.py have tons more features to explore.
Keep experimenting, keep coding, and most importantly, have fun! If you hit any snags, the discord.py documentation and Discord developer community are fantastic resources. Now go forth and bot on!