Discord.py load_extension Enable tracemalloc to get the object allocation traceback" - discord.py

While running the main.py file i get this error "main.py:15: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
client.load_extension(f"commands.{filename[:-3]}")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback"
Main.py File
import discord
from discord import *
from discord.ext import commands
import os
import asyncio
client = commands.Bot(command_prefix="-", help_command=None,intents=discord.Intents.all())
token = os.getenv("TOKEN")
#client.event
async def on_ready():
print("Rhino Bot is online")
for filename in os.listdir('./commands'):
if filename.endswith('.py'):
client.load_extension(f"commands.{filename[:-3]}")
print(f"{filename[:-3]} loaded")
client.run(token)
commands/ban.py
import discord
from discord.ext import commands
import asyncio
import random
class ban(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
#commands.cooldown(1,4,commands.BucketType.user)
#commands.has_permissions(ban_members = True)
async def ban(self, ctx,member : discord.Member,*,reason= "No Reason Provided"):
guild = ctx.guild
try:
embed=discord.Embed(title="Ban 🔨", description=(f"You Have Been Banned From the {guild.name}, Because:"+reason), color=discord.Color.random())
embed.set_author(name='Rihno Bot',
icon_url='https://cdn.discordapp.com/attachments/935411433380917309/938391346283163678/images.png')
await member.send(embed=embed)
await member.ban(reason=reason)
except:
embed=discord.Embed(title="Banned 🔨", description=(member.mention + f" has been banned from the server, Because:"+reason), color=discord.Color.random())
embed.set_author(name='Rihno Bot',
icon_url='https://cdn.discordapp.com/attachments/935411433380917309/938391346283163678/images.png')
embed=discord.Embed(title='Error', description=("dms are closed so i couldn't dm them ❌"))
embed.set_author(name='Rihno Bot',
icon_url='https://cdn.discordapp.com/attachments/935411433380917309/938391346283163678/images.png')
await ctx.send(embed=embed)
await member.ban(reason=reason)
def setup(client):
client.add_cog(ban(client))
What should i do? discord.py version using 2.1.0
and platform is replit.................

It's because you added load_extension part without await it so that's why it's causing coroutine error. You can fix this in two ways:
Just add this to your place where you added client.load_extension(f"commands.{filename[:-3]}")
await client.load_extension(f"commands.{filename[:-3]}")
Can even do something like this, if you don't wanna await:
for filename in os.listdir('./commands'):
if filename.endswith('.py'):
client.load_extension(f"commands.{filename[:-3]}")
#client.event
async def on_ready():
print("Rhino Bot is online")

Related

Discord.py ghost TEST command

The bot has a "ghost" test command. I do not create it anywhere, yet still it shows up in the slash command menu. If I try to run it I get an error, that the command doesn't exist.
import asyncio
import discord
from discord.ext import commands
class Bot(commands.Bot):
def __init__(self):
intents = discord.Intents.all()
super().__init__(command_prefix="$", intents=intents)
async def setup_hook(self):
await self.tree.sync()
print(f"Synced slash commands for {self.user}.")
async def on_command_error(self, ctx, error):
print(error)
await ctx.reply(error, ephemeral=True)
bot = Bot()
async def main():
async with bot:
await bot.start('Token')
asyncio.run(main())
If I try to create it I get two /test commands
import asyncio
import discord
from discord.ext import commands
class Bot(commands.Bot):
def __init__(self):
intents = discord.Intents.all()
super().__init__(command_prefix="$", intents=intents)
async def setup_hook(self):
await self.tree.sync()
print(f"Synced slash commands for {self.user}.")
async def on_command_error(self, ctx, error):
print(error)
await ctx.reply(error, ephemeral=True)
bot = Bot()
#bot.hybrid_command(name="test", with_app_command=True, description="Testing")
async def test(ctx: commands.Context):
await ctx.defer(ephemeral=True)
await ctx.reply("hi!")
async def main():
await bot.start('Token')
asyncio.run(main())
Where does the first test command come from?
Showing in the menu\Two /test commands

Discord.py Repeat message, delete command

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

error message when using process_commands

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

#bot.command() doesn't run - No errors show up

import discord
from discord.ext import commands
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
intents = discord.Intents.all()
client = discord.Client(intents=intents)
#bot.command()
async def hi(ctx):
await ctx.send("hi")
client.run(TOKEN)
I'm trying to get my bot to respond "hi" when a user runs command "!hi". The problem is that the command doesn't run and no errors show up as well. The code within the .py file is exactly as it is shown (except TOKEN is replaced with an actual Token)
You're running client, and decorating the command with bot.command(), you have to either use discord.Client or commands.Bot not both.
import discord
from discord.ext import commands
intents = discord.Intents.all()
bot = commmands.Bot(command_prefix=command.when_mentioned_or("!"), intents=intents)
#bot.command()
async def hi(ctx):
await ctx.send("Hi")
# You can also use events with `commands.Bot`
#bot.event
async def on_ready():
print("Ready")
bot.run("TOKEN")
The problem here is that you're using both discord.Client and commands.Bot
here's how to fix it:
import discord
from discord.ext import commands
TOKEN = "Your Token"
Intents=discord.Intents.all()
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'), Intents=Intents)
#bot.command()
async def hi(ctx):
await ctx.send("hi")
client.run(TOKEN)

"Error 'Self' is not defined" in member.edit

I'm having issues with my code saying
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: edit() missing 1 required positional argument: 'self'
when I run the command. Self shouldn't need to be defined, right?
Also, when I do add self I get an issue with ctx.
The code:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="/")
#client.command(pass_context=True)
async def join(ctx, member=discord.Member):
channel = ctx.author.voice.channel
await channel.connect()
await member.edit(mute=True)
#client.command(pass_context=True)
async def leave(ctx):
await ctx.voice_client.disconnect()
client.run("Token")
I Managed to find the problem and fixed it.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="/")
#client.command()
async def join(ctx):
channel = ctx.author.voice.channel
await channel.connect()
await ctx.author.edit(mute=True)
#client.command()
async def leave(ctx):
await ctx.voice_client.disconnect()
client.run("Token")
the problem is, you included member on your funcion. If you want it to send, edit, or do something with the message author just do ctx.author and it will be set on the author of the message.

Resources