Discord bot commands not working (Python) - python

I am currently using python to code my first discord bot. While trying to write a command, I saw that I was unable to do this. This code:
import os
import random
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = 'NzQxMjA2OTQzMDc4ODA5NjEy.Xy0Mwg.Shkr9hHvkn-y4l5ye1yTHYM3rQo'
client = discord.Client()
#client.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(f'Hi {member.name}, welcome to my Discord server!')
pp = commands.Bot(command_prefix='!')
messages = ["hello", "hi", "how are you?"]
#pp.command(name = "swear")
async def swear(ctx):
await ctx.send(rand.choice(messages))
client.run(TOKEN)
is not outputting anything in the discord application when I type !swear. The bot is online, and working normally for other codes such as:
#client.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(f'Hi {member.name}, welcome to my Discord server!')
Here is the full code:
import discord
import os
import random
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = (##my token spelled out)
client = discord.Client()
#client.event
async def on_ready():
print('im in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hello'):
await message.channel.send('Hi there!')
elif message.content.startswith("Is Ethan's mum gay?"):
await message.channel.send("Yep, 100%!")
elif message.content.startswith("What are you doing?"):
await message.channel.send(f"Step {message.author}")
elif 'happy birthday' in message.content.lower():
await message.channel.send('Happy Birthday! 🎈🎉')
#client.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(f'Hi {member.name}, welcome to my Discord server!')
pp = commands.Bot(command_prefix='!')
messages = ["hello", "hi", "how are you?"]
#pp.command(name = "swear")
async def swear(ctx):
await ctx.send(rand.choice(messages))
client.run(TOKEN)
Does anyone know how I can fix my problem?

Client() and Bot() are two methods to create bot and using both at the same time is wrong.
Using Client() and Bot() you create two bots but they would need client.run(TOKEN) and pp.run(TOKEN) to run together - but it makes problem to start them at the same time and it can make conflict which one should get user message.
Bot() is extended version of Client() so you need only Bot() and use
#pp.event instead of #client.event
pp.run(TOKEN) instead of client.run(TOKEN)
pp.user instead of client.user
EDIT:
And you have to define pp before all functions. Like this
import random
from discord.ext import commands
TOKEN = 'TOKEN'
pp = commands.Bot(command_prefix='!')
#pp.event
async def on_ready():
print('im in as {}'.format(pp.user))
#pp.event
async def on_message(message):
if message.author == pp.user:
return
if message.content.startswith('hello'):
await message.channel.send('Hi there!')
elif message.content.startswith("Is Ethan's mum gay?"):
await message.channel.send("Yep, 100%!")
elif message.content.startswith("What are you doing?"):
await message.channel.send(f"Step {message.author}")
elif 'happy birthday' in message.content.lower():
await message.channel.send('Happy Birthday! 🎈🎉')
#pp.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(f'Hi {member.name}, welcome to my Discord server!')
messages = ["hello", "hi", "how are you?"]
#pp.command(name = "swear")
async def swear(ctx):
await ctx.send(rand.choice(messages))
pp.run(TOKEN)

Related

Discord bot in python- message not sending

Below is the current code. I'm kinda new to python, but my previous bot with virtually the same code ran perfectly fine, so i don't understand why it's not running. The bot will turn on and show as "online" in Discord, but won't send the message.
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = 'token'
client = discord.Client(intents=discord.Intents.all())
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
async def on_message(message):
channel = message.channel
content = message.content
user = message.author
userid = message.author.id
if content == "hello":
await client.send_message(channel, "rude response")
client.run(TOKEN)
For your code to work you need to add a decorator to every method.
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = 'token'
client = discord.Client(intents=discord.Intents.all())
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
# You forgot decorator here
#client.event
async def on_message(message):
channel = message.channel
content = message.content
user = message.author
userid = message.author.id
if content == "hello":
await client.send_message(channel, "rude response")
client.run(TOKEN)
on_message here is not decorated with #client.event hence you just define a function and never call it. Add the decorator to make a listener out of it
#client.event
async def on_message(message):
...

No error but it is not running HELP Discord.py

i want to make a discord bot but i cant run it.
idk what to do
it just runs
and no log
idk REALLY what to do
import discord
from discord.ext import commands
import os
import keep_alive
client = commands.Bot(command_prefix="!")
token = os.environ.get('Token')
GUILD = os.environ.get('Guild')
async def on_ready():
print(f'{client.user} is connected')
#client.command()
async def dm(ctx, member: discord.Member):
await ctx.send('what do u want to say bitch!')
def check(m):
return m.author.id == ctx.author.id
massage = await client.wait_for('massage', check=check)
await ctx.send(f'send massage to {member} ')
await member.send(f'{ctx.member.mention} has a massage for you: \n {massage}')
#client.event
async def on_member_join(member):
channel = discord.util.get(member.Guild, name='general')
await channel.send(f'Hey welcome to my server {member.mention}, hope you enjoy this server!')
keep_alive.keep_alive()
client.run(token)
client.close()
i dont know what to do anymore
I tried everything i could i ran it in pycharm
vscode
nothing works
There's a lot of errors on your code. so I fixed it
First thing is your client events, keep_alive, client.run, also why did you put client.close()
import os, discord
import keep_alive
from discord.ext import commands
client = commands.Bot(command_prefix="!")
token = os.environ.get('Token')
GUILD = os.environ.get('Guild')
#client.event # You need this event
async def on_ready():
print(f'{client.user} is connected')
"""
client.wait_for('massage') is invalid. Changed it into 'message'. Guess it is a typo.
You can replace this command with the new one below.
"""
#client.command()
async def dm(ctx, member: discord.Member):
await ctx.send('what do u want to say bitch!')
def check(m):
return m.author.id == ctx.author.id
massage = await client.wait_for('message', check=check)
await ctx.send(f'send massage to {member} ')
await member.send(f'{ctx.member.mention} has a massage for you: \n {massage}')
"""
I also moved this on_member_join event outside because it blocks it.
"""
#client.event
async def on_member_join(member):
channel = discord.util.get(member.Guild, name='general')
await channel.send(f'Hey welcome to my server {member.mention}, hope you enjoy this server!')
"""
I put the keep_alive call outside because the function blocks it in your code.
And also removed client.close() to prevent your bot from closing
"""
keep_alive.keep_alive()
client.run(token)
For the dm command. Here it is:
#client.command()
async def dm(ctx, member:discord.Member=None):
if member is None:
return
await ctx.send('Input your message:')
def check(m):
return m.author.id == ctx.author.id and m.content
msg = await client.wait_for('message', check=check) # waits for message
if msg:
await member.create_dm().send(str(msg.content)) # sends message to user
await ctx.send(f'Message has been sent to {member}\nContent: `{msg.content}`')
Sorry, I'm kinda bad at explaining things, also for the delay. I'm also beginner so really I'm sorry

Can't run a join function because of a on_message event

i'm making a discord bot with python. I have some issues about running using #client.command and #client.event at the same time.
Here is the code:
when I comment the #client.event before the on message function, the join command run. This function cause a particular issue, do you know guys where it can come from? Thank you guys
import discord
import random
from discord.utils import get
from discord.ext import commands
#client.command(pass_context=True)
async def join(ctx):
channel = ctx.author.voice.channel
await channel.connect()
#client.command(pass_context=True)
async def leave(ctx):
await ctx.voice_client.disconnect()
#client.event
async def on_ready():
print("We have logged as {0.user}".format(client))
#client.event
async def on_message(message):
user = message.author.id
if message.content.lower() == "!poisson":
await message.delete()
with open('myimage.png', 'rb') as f:
picture = discord.File(f)
await message.channel.send(file=picture)
Put await client.process_commands(message) at the end of on_message()
If you're using on_message, then normal commands will be overridden unless you use process_commands.

Discord bot won't go online

I've just started learn python and my discord bot won't go online. it just said
" Process exit with exit code 0". And there's no error with the code.
here's my code. enter image description here
Add await client.process_commands(ctx) and #client.event don't need parentheses(). Use the code given below:
#client.event
async def on_message(ctx):
if ctx.author == client.user:
return
await client.process_commands(ctx)
Use this entire code if it still not working:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
#bot.event
async def on_ready():
print('We are logged in!')
#bot.event
async def on_message(message):
if message.author==bot.user:
return
await bot.process_commands(message)
#bot.command()
async def ping(message) :
await message.channel.send("Pong!!")
bot.run("TOKEN")
You should try this instead
import os
import discord
from discord.ext import commands
discord_token = "Your Token"
client = discord.Client()
bot = commands.Bot(command_prefix="s!")
#bot.event
async def on_ready():
print("running")
bot.run(discord_token)
#bot.command()
async def on_ready():
print("running")
bot.run(discord_token)
and the output should be running
You should try this instead
import os
import discord
from discord.ext import commands
discord_token = "Your Token"
client = discord.Client()
bot = commands.Bot(client_prefix="!")
#client.command()
async def on_ready():
print("running")
bot.run(discord_token)
The code you gave is wrong, this is correct:
import os
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!") # you don't need an extra discord.client Bot is enough
token = os.getenv("TOKEN")
#you should not run the program here you should run it at last
#bot.event #no need for brackets
async def on_ready():
print("running")
#bot.event
async def on_message(ctx):
if ctx.author == client.user:
return
#bot.command(name="span",description="YOUR DESCRIPTION HERE") # it is command and not commands
async def span_(ctx,amount:int,*,message):
for i in range(amount):
await ctx.send(message)
bot.run(token) #you should run the bot now only and this will work perfectly!
You can find the the documentation for discord.py here.

the commands of my discord bot is not working except 1

import discord
import os
import requests
import json
import random
from random import randint
from replit import db
from discord.ext import commands
client = discord.Client()
bot = commands.Bot(command_prefix='.')
#client.event
async def on_ready():
print(f'{client.user.name} működik!')
await client.change_presence(activity=discord.Game(name='egy bot vagyok'))
#client.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(
f' {member.name}, itt van!'
)
#bot.command()
async def test(ctx, arg):
await ctx.send(arg)
print(f'haha')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('ping'):
await message.channel.send("pong")
if message.content.startswith("shrug"):
await message.channel.send('¯\_(ツ)_/¯')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('.pic'):
await message.channel.send(file=discord.File('combo-0.png'))
token = os.environ.get("secret")
client.run(token)
im a beginner in discord bot programming
this is my whole code for my discord bot and all of the commands are not working except one
te .pic command
all of the commands worked until now and i dont know why they dont work
if i would get some help i would be happy :D
(sorry for my bad english, english isnt my first language)
You cannot have multiple on_message events, only the last one will be registered. You have to combine them into one
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('ping'):
await message.channel.send("pong")
if message.content.startswith("shrug"):
await message.channel.send('¯\_(ツ)_/¯')
if message.content.startswith('.pic'):
await message.channel.send(file=discord.File('combo-0.png'))
You can't mix up the discord.Client() and commands.Bot clients like this.
commands.Bot is a subclass of discord.Client, so you should be able to do everything that you could do with discord.Client() with commands.Bot()
bot = commands.Bot('!')
#bot.event
async def on_ready():
print('ready')
#bot.command()
async def ping(ctx):
await ctx.send('pong')
For help with the rewrite discord.ext.commands, there are a butt ton of tutorials on the internet.

Categories