I tried making a discord bot and stumbled across an issue, the bot does not respond to commands and I have no clue what's wrong.
Here's my code
import discord
from discord.ext import commands
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
await client.change_presence(activity=discord.Game(name="Python"))
async def on_message(self, message):
print('Message from {0.author}: {0.content}'.format(message))
await bot.process_commands(message)
client = MyClient()
client.run("Token Here")
bot = commands.Bot(command_prefix='!')
#bot.command()
async def test(ctx):
await ctx.send("Sup")
You are currently mixing a discord.Client with a commands.bot.
Discord.py provides multiples ways to creates bots that are not compatibles each other.
Moreover, client.run is blocking, and should be at the end of your script.!
import discord
from discord.ext import commands
class MyClient(commands.Bot):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
await client.change_presence(activity=discord.Game(name="Python"))
async def on_message(self, message):
print('Message from {0.author}: {0.content}'.format(message))
await self.process_commands(message)
client = MyClient(command_prefix='!')
#client.command()
async def test(ctx):
await ctx.send("Sup")
client.run("...")
Note that you are not obligated to subclass the commands.Bot class given by the library.
Here is an other exemple that don't use subclassing:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='!')
#client.event
async def on_ready():
print('Logged on as {0}!'.format(client.user))
await client.change_presence(activity=discord.Game(name="Python"))
#client.event
async def on_message(message):
print('Message from {0.author}: {0.content}'.format(message))
await client.process_commands(message)
#client.command()
async def test(ctx):
await ctx.send("Sup")
client.run("...")
Using the second approach might be beneficial if you just started to learn dpy, and can work when you dont have a lot of commands.
However, for bigger projects, the first approach will help to organise your bot by using cogs for commands and events.
Related
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.
Hello i try a lot commands to fix it but the bot is doing nothing
Here is my Code. The File are bot.py
import discord
import os
from discord.ext import commands
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
async def on_message(self, message):
print('Message from {0.author}: {0.content}'.format(message))
client = MyClient()
#client.event
async def on_ready():
print(f'{client.user.name} Test!')
###############
bot = commands.Bot(command_prefix="!")
#bot.event
async def on_guild_join(guild):
if guild.system_channel:
await guild.system_channel.send("Test")
##client.event
#async def on_member_join(member):
# await ctx.author.send("Welcome!")
##*#client.event
#async def on_member_join(member):
# await member.create_dm()
# await member.send(
# f'Hallo{member.name}, Willkommen'
# )
Why is it not working i try a lot Commands/models whatever.
I use Notepad++ to programming. Give it a better Programm to programming with Python? Maybe what for Beginners?
You cant use both discord.Client and commands.Bot, choose one of them.
commands.Bot is basically the same as discord.Client but with the extra commands feature
-> Docs
# so first remove the client part in your code
# and define the Bot | you can name it 'bot' or 'client'
# bot = commands.Bot(command_prefix="!")
# is the same as
# client = commands.Bot(command_prefix="!")
# also make sure to enable Intents
intents = discord.Intents.default()
intents.member = True
bot = commands.Bot(command_prefix="!", intents=intents)
#now you can add events
#bot.event
async def on_guild_join(guild):
if guild.system_channel:
await guild.system_channel.send("Test")
#bot.event
async def on_member_join(member):
await member.send("welcome!")
# and commands
#bot.command()
async def slap(ctx, member: discord.Member):
await ctx.send(f"{ctx.author} gave {member} a slap")
# at the very end run your bot
bot.run('BOT TOKEN')
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.
So I'm making a basic bot command that responds with what the player said, like doing !test code will make the bot respond with 'code'. For some reason, nothing happens when the command is run. I even put a print inside of it to see if it was actually being run, and it wasn't. Here's my code:
import discord
from discord.ext import commands
client = discord.Client()
bot = commands.Bot(command_prefix="!")
#client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
print("-"*16)
game = discord.Game("Discord")
await client.change_presence(status=discord.Status.online, activity=game)
#bot.command()
async def test(ctx, arg):
await ctx.send(str(arg))
client.run('token here')
Any help is appreciated.
try this out:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="!")
#client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
print("-"*16)
game = discord.Game("Discord")
await client.change_presence(status=discord.Status.online, activity=game)
#client.command()
async def test(ctx, *, arg):
await ctx.send(str(arg))
client.run('token here')
heres what you got wrong:
client = discord.Client()
bot = commands.Bot(command_prefix="!")
You had 2 separate handlers for the bot, if you use commands you only need the bot = commands.Bot(command_prefix="!") line, in this case you had the bot handler for commands but you were running client
The code below runs as expected when tested using Python3.7 ...
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="!")
#client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
print("-"*16)
game = discord.Game("Discord")
await client.change_presence(status=discord.Status.online, activity=game)
#client.command()
async def test(ctx, *arg):
await ctx.send(str(arg))
client.run('token here')
Your code as posted has an await statement outside of a function
......
print("-"*16)
game = discord.Game("Discord")
await client.change_presence(status=discord.Status.online, activity=game)
.......
Also change
#bot.command()
async def test(ctx, arg):
TO:
#bot.command()
async def test(ctx, *arg):
For an explanation as to why you pass *arg and not arg:
args-and-kwargs
You can't run client and bot together if want bot to run the last line of code must be bot.run('your token') if you want client to run use client.run('your token')
I'm setting up a simple Python Discord bot, but it only seems to respond to one event/command. It only responds to when someone says "supreme sauce" it sends "raw sauce" but doesn't respond to anything else such as ".ping" or ".clear".
Is there anything that I'm doing wrong?
My code:
import discord
from discord.ext import commands
import time
client = commands.Bot(command_prefix = '.')
#client.event
async def on_ready():
print(f'{client.user} has successfully connected to Discord!')
#client.event
async def on_message(message):
if 'supreme sauce' in message.content:
await message.channel.send('raw sauce')
#client.command()
async def ping(ctx):
await ctx.send(f'Pong! {round(client.latency * 1000)}ms')
#client.command
async def clear(ctx, amount=10):
await ctx.channel.purge(limit=amount)
client.run('My Token')
on_message takes priority over commands.
If you want both things to happen, do like this:
async def on_message(message):
if message.author == bot.user: return #Makes sure it can't loop itself when making messages
await bot.process_commands(message)
#rest of your code here
This makes it so that when a message is sent, it will check if that message is a command and go from there, then it will execute the on_message code like normal