So I am trying to make a discord.py echo/say command, but no response or errors are happening, if you know how to fix this please help me out!
import discord, os, keep_alive, asyncio, datetime, pytz, requests
from discord.ext import tasks, commands
client = commands.Bot(
command_prefix=':',
self_bot=True
)
async def on_ready():
client.remove_command('help')
await client.change_presence(status=discord.Status.online, activity=discord.Game("TEST"))
#client.command()
async def echo(ctx, *,args):
if ctx.message.author.id in [782258096210051102]:
await ctx.send(args)
await ctx.message.delete()
else:
await ctx.send("Bot developers only :<")
keep_alive.keep_alive()
client.run(os.getenv("TOKEN"), bot=False)
It's not working because the ctx.author is None, to fix that enable intents.members
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(..., intents=intents)
Also make sure to enable them in the developer portal
Reference
Uhhhhhh it is better to do something like
#bot.command()
async def echo(ctx,*,arg):
#the star is required
if ctx.authir.id==782258096210051102:
await ctx.send(arg)
else:
await ctx.send("devs only :<")
You can use ' '.join(ctx.message.content.split()[1:]) to join all words after the first space. So something like:
#client.command()
async def echo(ctx, *args):
await ctx.send(' '.join(ctx.message.content.split()[1:]))
To See Where The Problem Is From First Try:
#client.command()
async def echo(ctx, *,args):
await ctx.send(args[0])
await ctx.message.delete()
Ok so actually you have need to do this:
#client.command(name='echo')
async def echo(ctx, *, what_bot_need_to_say: str):
if ctx.message.author.id == 782258096210051102:
await ctx.channel.purge(limit=1) # This delete an message in the channel
await ctx.send(what_bot_need_to_say) # This the echo
else:
await ctx.send("Bot developers only :<")
#bot.command()
async def say(ctx, *, msg):
await ctx.send(msg)
Just copy me it is the simplest and gives the correct format
import discord
from discord.ext import commands
bot = commands.Bot('?')
#bot.command()
async def repeat(ctx,*,repeat:str):
if ctx.author.id == 782258096210051102:
await ctx.send(f"{repeat}")
await ctx.message.delete()
return
else:
await ctx.send("Only devs")
return
#bot.event
async def on_ready():
print("bot online")
bot.run("YOUR_TOKEN_HERE")
try this:
import discord, os, keep_alive, asyncio, datetime, pytz, requests
from discord.ext import tasks, commands
client = commands.Bot(
command_prefix=':',
self_bot=True
)
async def on_ready():
client.remove_command('help')
await client.change_presence(status=discord.Status.online, activity=discord.Game("TEST"))
#client.command()
async def echo(ctx, *,args):
if ctx.author.id in [782258096210051102]:
await ctx.send(args)
# await ctx.message.delete() # i am not sure of delete you can add it if you want
else:
await ctx.send("Bot developers only :<")
keep_alive.keep_alive()
client.run(os.getenv("TOKEN"), bot=False)
Related
I created a slash command under message cog to clean up messages, but it shows that 'the application is not responding' in discord
Here is my code:
class Message(InitCog):
# clean messages
#app_commands.command(name='clean', description='clean messages')
#app_commands.describe(num='number of message')
#commands.has_permissions(manage_channels=True)
async def clean(self, ctx, *, num: int):
await ctx.channel.purge(limit=num)
await discord.Interaction.response.defer(ephemeral=True)
await discord.Interaction.followup.send(f'deleted {num} messages')
async def setup(client):
await client.add_cog(Message(client))
and main code:
import asyncio
import discord
import os
from discord.ext import commands
client = commands.Bot(command_prefix='?', intents=discord.Intents.all())
async def setup_hook():
for Filename in os.listdir('./cmds'):
if Filename.endswith('.py'):
await client.load_extension(f'cmds.{Filename\[:-3\]}')
#client.event
async def on_ready():
sync = await client.tree.sync()
print(f"bot logged as {client.user}")
print(f'synced {len(sync)} commands')
async def main():
await setup_hook()
await client.start(jdata\['Token'\])
if __name__ == "__main__":
asyncio.run(main())
Already solved , Use interaction.channel.purge instead of ctx.channel.purge
#app_commands.command(name='clean', description='clean messages')
#app_commands.describe(num='number of message')
#commands.has_permissions(manage_channels=True)
async def clean(self, interaction: discord.Interaction, num: int):
try:
await interaction.channel.purge(limit=num)
await interaction.response.defer()
await interaction.followup.send(f'deleted {num} messages')
except Exception as e:
print(e)
I am trying to delete the command message (the one sent by the user not by bot)
Ive tried it like this.
#bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content.startswith("-"):
wait(5)
await message.delete()
and this
#bot.command()
async def creator(ctx, message):
await ctx.send(f"Example text")
wait(5)
await message.delete()
but none of them work. If you know why please post a solution. Thanks!
In the first code :
import time
#bot.event
async def on_message(message):
if message.author.bot : return
if message.content.startswith("-"):
time.sleep(5)
await message.delete()
Second Code
import time
#bot.command()
async def creator(ctx):
await ctx.send("Example text")
time.sleep(5)
await ctx.message.delete()
If you are using the both of on_message and commands in your bot,
You may want to add this in the end of on_message Event So your bot will handle the on_message event, Then it goes to process commands.
Without it the bot commands wont work .
await bot.process_commands(message)
Eg :
#bot.event
async def on_message(message) :
await message.channel.send("Example")
await bot.process_commands(message)
I've gotten it to repeat the message in total, but how do I have it remove the command prefix, and delete the message?
import discord
import os
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('.say'):
await message.channel.send(message.content)
client.run(os.getenv('TOKEN'))
To get rid of the bot sending the command prefix you can use [4:] when sending so the first four characters are not sent!
And to delete the message of the user you can use the command: await message.delete()
So the complete code would be:
import discord
import os
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('.say'):
await message.channel.send(message.content[4:])
await message.delete()
client.run(os.getenv('TOKEN'))
I would check out the discord.py documentation linked here
I would recommend using discord.ext.commands here is your code made into a commands.Bot instead of discord.client
use .say LONGMESSAGE HERE to invoke the command
import discord
from discord.ext import commands
import os
bot = commands.Bot(command_prefix='.')
#bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#bot.command()
async def say(ctx,* , data:str = None):
if not data:
return await ctx.send('please enter some data')
await ctx.message.delete()
await ctx.send(data)
bot.run(os.getenv('TOKEN'))
Read more
I get an error message because of the command process_commands and the commands doesn't work, while the evnts do work properly.
import discord
from discord import commands
import os
bot = commands.Bot(command_prefix="!")
client = discord.Client()
#client.event
async def on_ready():
print('Logged in as 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('Hello!')
#here comes the error message
await bot.process_commands(message)
#this command doesn't work
#bot.command()
async def testymesty(ctx):
await ctx.send('test')
keep_alive()
client.run(os.environ['TOKEN'])
Simple error, you defined client as commands.bot then its going to be :
await client.process_commands(message)
decide between client and bot.
Don't use client and bot at the same time
What is causing the error in the init class?
I'm trying to declare a class, but I'm not sure what to do.
(It is discord.ext)
my code is:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='!')
token = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
#Client = command_prefix
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
#client.command()
async def ping(ctx):
await ctx.send('pong')
async def on_message(message):
#commands.Bot(name="<<kick", pass_context= True)
#commands.has_permissions(administrator=True)
async def _kick(ctx, *, username: discord.Member, reason=None):
await user_name.kick(reason=reason)
await ctx.send(str(user_name) + '\n```User was kick!```')
client.run(token)
error is
TypeError: __init__() missing 1 required positional argument: 'command_prefix'
Thanks for reading.
You have
#commands.Bot(name="<<kick", pass_context= True) which should be #client.command(name="kick", pass_context= True) you also had an indent error (async def on_message(message):) which usually comes at the end of your commands. await ctx.send(str(user_name) + '\n```User was kick!```') here you refer to user_name instead of username, which you defined in the function.
I tested the code and this is what it should look like when fixed:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='!')
token = "XXXXXXXXXXXXXXXX"
# Client = command_prefix
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
#client.command()
async def ping(ctx):
await ctx.send('pong')
#client.command(name="kick", pass_context=True)
#commands.has_permissions(administrator=True)
async def _kick(ctx, *, username: discord.Member, reason=None):
await username.kick(reason=reason)
await ctx.send(str(username) + '\n```User was kick!```')
client.run(token)