I am a new programmer, trying to make a discord bot with python. Today I closed PyCharm, and did not close the running program first. As soon as I did that, the discord.py bot was still running in discord. All the commands were working with it, and the bot was online. When I restarted Pycharm, I ran the program again, and then it started working twice, and when I terminated the program, the bot was still running in discord. Here is my code and an image of what is happening-
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='r!', case_insensitive=True)
client.remove_command('help')
#client.event
async def on_ready():
print(f'{client.user.name} is ready')
#client.command()
async def help(ctx):
embed = discord.Embed(
title='Training Bureau Bot',
description='''These are all the commands you can use from this bot:
----------------------------------------------------------''',
color=discord.Colour.gold()
)
embed.set_thumbnail(url='https://cdn.discordapp.com/icons/820075295947096154/ebcccb9506e73b0dec8818249e6cba0c.webp?size=128')
embed.add_field(
name='r!help',
value='`Shows all the commands.`',
inline=True
)
await ctx.send(embed=embed)
#client.command()
async def discharge(ctx):
allowed_people = discord.utils.get(ctx.guild.roles, name='Training Bureau Personnel')
if allowed_people in ctx.author.roles:
embed = discord.Embed(
title='Discharge',
description='''If you want to discharge, state your reason below.
---------------------------------------------------------''',
color=discord.Colour.gold()
)
embed.set_thumbnail(
url='https://cdn.discordapp.com/icons/820075295947096154/ebcccb9506e73b0dec8818249e6cba0c.webp?size=128')
await ctx.send(embed=embed)
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel and \
msg.content.lower()
msg = await client.wait_for('message', check=check, timeout=60)
embed_2 = discord.Embed(
title='Successful!',
description='Your discharge has been successfully logged. Please wait for the HICOM to accept/deny it.',
color=discord.Colour.green()
)
embed_2.set_thumbnail(
url='https://cdn.discordapp.com/icons/820075295947096154/ebcccb9506e73b0dec8818249e6cba0c.webp?size=128')
discharge_logs = client.get_channel(933708007097905183)
embed_3 = discord.Embed(
title='Discharge Notice',
description=f'{msg.author.display_name} has written a discharge notice with the reason: "{msg.content}"\n' + '----------------------------------------------------------------------------',
color=discord.Colour.gold()
)
embed_3.set_thumbnail(
url='https://cdn.discordapp.com/icons/820075295947096154/ebcccb9506e73b0dec8818249e6cba0c.webp?size=128')
await discharge_logs.send(embed=embed_3)
await ctx.send(embed=embed_2)
else:
embed = discord.Embed(
title='No permissions',
description='You are not allowed to execute this command. (If you think this is a mistake, DM Burger1372.',
color=discord.Colour.red()
)
await ctx.send(embed=embed)
client.run(TOKEN)
Please tell me how to fix this. If you could also tell me how I can make the code more efficient, it would be appreciated. :)
Related
I started learning python today and made a Discord bot. I have a few problems:
If message.author == was used in the on_message, but the bot continued to reply to itself.
Afterwards, a new bot was created with a new token and the code didn't work.
I searched a lot on this site and Google. I didn't find any solution. It's okay to modify my code. Everything is from the internet, so it can be a mess. Please help me.
import discord
import asyncio
from discord.ext import commands
client = discord.Client()
bot = commands.Bot(command_prefix="!")
#bot.event
async def on_ready():
print('Loggend in Bot: ', bot.user.name)
print('Bot id: ', bot.user.id)
print('connection was succesful!')
print('=' * 30)
#client.event
async def on_message(message) :
if on_message.content.startswith('!의뢰'):
msg = on_message.channel.content[3:]
embed = discord.Embed(title = "브리핑", description = msg, color = 0x62c1cc)
embed.set_thumbnail(url="https://i.imgur.com/UDJYlV3.png")
embed.set_footer(text="C0de")
await on_message.channel.send("새로운 의뢰가 들어왔습니다", embed=embed)
await client.process_commands(message)
client.run("My bot's token.")
Your code was messy, but it should work now. I included comments to let you know how everything works. I think the good starting point to making your own bot is reading documentation. Especially Quickstart that shows you a simple example with explanation.
Write !example or hello to see how it works.
import discord
import asyncio
from discord.ext import commands
# you created 'client' and 'bot' and used them randomly. Create one and use it for everything:
client = commands.Bot(command_prefix="!") # you can change commands prefix here
#client.event
async def on_ready(): # this will run everytime bot is started
print('Logged as:', client.user)
print('ID:', client.user.id)
print('=' * 30)
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hello'): # you can change what your bot should react to
await message.channel.send("Hello! (This is not a command. It will run everytime a user sends a message and it starts with `hello`).")
await client.process_commands(message)
#client.command()
async def example(ctx): # you can run this command by sending command name and prefix before it, (e.g. !example)
await ctx.send("Hey! This is an example command.")
client.run("YOUR TOKEN HERE")
Code:
import os
import discord
import random
from discord.ext import commands
GUILD = os.getenv('DISCORD_GUILD')
client2 = commands.Bot(command_prefix = '')
#client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} has connected to '
f'{guild.name}'
)
#client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
bot = commands.Bot(command_prefix='$')
#client2.command(pass_context = True)
async def mute(ctx, member: discord.Member):
if ctx.message.author.server_permissions.administrator or ctx.message.author.id == '194151340090327041':
role = discord.utils.get(member.server.roles, name='Muted')
await bot.add_roles(member, role)
embed=discord.Embed(title="User Muted!", description="**{0}** was muted by **{1}**!".format(member, ctx.message.author), color=0xff00f6)
await bot.say(embed=embed)
else:
embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xff00f6)
await bot.say(embed=embed)
client.run(os.getenv('TOKEN'))
I am trying to create a bot that mutes people. This is my 1st week in learning the discord API. I copied the mute function from a website so I didn't code everything myself. I'm having some trouble with the command. The error is:
NameError: name 'commands' is not defined
But I have seen other people do this and not get an error so I have no idea what the problem is.
Thanks a lot!
As mentioned before, you are going around with definitions that don't exist/that you shouldn't use.
First: Decide between client or bot and use the original handling, not somehow client2 etc.
Second: To use the commands, import from discord.ext import commands.
Third: Since you are now using client the commands have to be adapted. Also you don't use client.say or bot.say anymore, but ctx.send.
Fourth: You can't use multiple on_ready events, combine them or just use one.
Fifth: Please have a look at the mute command as yours contained many errors and requested things in the wrong way. You can take a look at other StackOverflow questions and answers as just copy and pasting another answer is not really useful...
Have a look at the full/final code:
from discord.utils import get # New import
import discord
from discord.ext import commands # New import
client = commands.Bot(command_prefix = 'YourPrefixHere') # Changes
TOKEN = "YourTokenHere" # Changes
#client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
#client.command()
async def mute(ctx, member: discord.Member):
if ctx.message.author.guild_permissions.administrator or ctx.message.author.id == 'Your_ID': # Changes
role = discord.utils.get(ctx.guild.roles, name='Muted') # Changes
await member.add_roles(role)
embed = discord.Embed(title="User Muted!",
description="**{}** was muted by **{}**!".format(member, ctx.message.author),
color=0xff00f6)
await ctx.send(embed=embed)
else:
embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xff00f6)
await ctx.send(embed=embed)
client.run(TOKEN) # Changes
I am trying to create a mute command for my Discord bot. I typed all the code out and I am pretty sure it should be working. However whenever I type N?mute nothing happens and subsequently nothing shows up in my command prompt. No error message, no nothing. I tried putting a print just after the async def mute() and that didn't show up either.
I have the following code:
import random
import discord
from discord.ext import commands
import urllib.parse
import os
import pymongo
from pymongo import MongoClient
client = commands.Bot(command_prefix='N?')
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.command()
#commands.has_role(743487766796697720)
async def mute(ctx, member: discord.Member):
role = discord.utils.get(ctx.guild.roles, name="Muted")
guild = ctx.guild
if role not in guild.roles:
perms = discord.Permissions(send_messages=False, speak=False)
await guild.create_role(name="Muted", permissions=perms)
await member.add_roles(role)
embed=discord.Embed(title="User Muted!", description="**{0}** was muted by **{1}**!".format(member, ctx.message.author), color=0xff00f6)
await message.channel.send(embed=embed)
else:
await member.add_roles(role)
embed=discord.Embed(title="User Muted!", description="**{0}** was muted by **{1}**!".format(member, ctx.message.author), color=0xff00f6)
await message.channel.send(embed=embed)
#mute.error
async def mute_error(ctx, error):
if isinstance(error, commands.MissingRole):
embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xff00f6)
await message.channel.send(embed=embed)
#mute.error
async def mute_error(ctx, error):
if isinstance(error, commands.BadArgument):
embed=discord.Embed(title="Permission Denied.", description="That is not a valid member.", color=0xff00f6)
await message.channel.send(embed=embed)
I tried making a kick command berore but after searching stackoverflow and dozen other websites to figure out why it didn't work, I gave up. Now I'm wondering why both client.commands have not worked so far. So far I have only used client.listen() and client.event() which both worked well. I don't know if it's simply an oversight or me doing something dumb but I'm at a loss right now. I'm fairly new to Discord.py so excuse my lack of skill :)
You dont have a message variable. Instead of message write ctx.
So
await message.channel.send(embed=embed)
should become
await ctx.channel.send(embed=embed)
To see the errors on your command prompt maybe first remove all you error commands. When I was making my bot, the error commands did not let me see errors on the command prompt. Maybe try that.
I fixed it by changing a bot.event to a bot.listen! Make sure you keep your events limited and mostly use listens and commands. I think having more than 1 bot.event killed my code. Thanks to everyone for their input and I hope this fixes it for whoever comes from Google :)
So I'm trying to remove the default help command from my discord bot but it shows my new one and the old one (Example Image), even though I have the code that removes it.
So to remove it I'm using
client = commands.Bot(command_prefix = '!',help_command=None)
and to replace it I have
#client.command()
async def help(ctx):
embed = discord.Embed(
colour = discord.Colour.orange()
)
embed.set_author(name='Saint Bot the Third Help Page')
embed.add_field(name='!remind', value='Reminds Shabby to get a PC', inline=False)
embed.add_field(name='!play', value='Gives you a random game to play', inline=False)
await ctx.send(embed=embed)
I have also tried using
client.remove_command("help")
but that did not work either
try this again, you will have to write all the errors thrown if there are any,
i have checked this code, and it is working fine.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '!')
client.remove_command("help")
#client.command()
async def help(ctx):
embed = discord.Embed(
colour = discord.Colour.orange()
)
embed.set_author(name='Saint Bot the Third Help Page')
embed.add_field(name='!remind', value='Reminds Shabby to get a PC', inline=False)
embed.add_field(name='!play', value='Gives you a random game to play', inline=False)
await ctx.send(embed=embed)
client.run(token)
I'm writing a custom help command that sends a embed DM to a user, that all works fine. As part of the command, I'm trying to make the bot react to the command message but I cannot get it to work, I've read the documentation but I still can't seem to get it to react as part of a command. Below is the what I'm trying to achieve:
#client.command(pass_context=True)
async def help(ctx):
# React to the message
author = ctx.message.author
help_e = discord.Embed(
colour=discord.Colour.orange()
)
help_e.set_author(name='The bot\'s prefix is !')
help_e.add_field(name='!latency', value='Displayes the latency of the bot', inline=False)
help_e.add_field(name='!owo, !uwu, !rawr', value='Blursed commands', inline=False)
await author.send(embed=help_e)```
You can use message.add_reaction() and also you can use ctx.message to add reaction to the message. Here is what you can do:
#client.command(pass_context=True)
async def help(ctx):
# React to the message
await ctx.message.add_reaction('✅')
author = ctx.message.author
help_e = discord.Embed(
colour=discord.Colour.orange()
)
help_e.set_author(name='The bot\'s prefix is !')
help_e.add_field(name='!latency', value='Displayes the latency of the bot', inline=False)
help_e.add_field(name='!owo, !uwu, !rawr', value='Blursed commands', inline=False)
sent_embed = await author.send(embed=help_e)