I got this exception7 How to fix it?
RuntimeWarning: coroutine 'job' was never awaited
self._run_job(job)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
from aiogram import Dispatcher, Bot, executor
from aiogram.types import Message,CallbackQuery
from asyncio import sleep
import schedule
bot = Bot(token)
dp = Dispatcher(bot)
#dp.message_handler(commands=['start'])
async def start(message : Message):
await bot.send_message(message.chat.id, message.text)
async def job():
await bot.send_message(626420006, 'job done!')
async def scheduler():
schedule.every(2).seconds.do(lambda : job())
while True:
schedule.run_pending()
await sleep(1)
if __name__ == "__main__":
dp.loop.create_task(scheduler())
executor.start_polling(dp,skip_updates=True)
I used another library aioschedule
from aiogram import Dispatcher, Bot, executor
from aiogram.types import Message,CallbackQuery
import asyncio
import time
import aioschedule as schedule
bot = Bot('')
dp = Dispatcher(bot)
#dp.message_handler(commands=['start'])
async def start(message : Message):
await bot.send_message(message.chat.id, message.text)
async def job():
print('hello')
await bot.send_message(626420006, 'job done!')
async def scheduler():
schedule.every(1).seconds.do(job)
# loop = asyncio.get_event_loop()
while True:
await schedule.run_pending()
await asyncio.sleep(2)
if __name__ == "__main__":
dp.loop.create_task(scheduler())
executor.start_polling(dp,skip_updates=True)
Related
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")
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)
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
I'm trying to understand how to use an async function inside another function:
I'm trying to send messages via Telegram whenever something happens during my code.
Telegram logger:
from telethon import TelegramClient, sync
import asyncio
async def msgtelegram(entity, msg,api_id=xxx, api_hash='xx'):
client = TelegramClient('Session', api_id, api_hash)
await client.start()
if not await client.is_user_authorized():
await client.sign_in('xxx')
await client.send_message(entity, msg)
await client.disconnect()
def func():
try:
print('hello!')
except:
await msgtelegram(entity, msg)
Calling await msgtelegram() outside of a function seems to work correctly.
Am I missing something or am I using async wrong?
Thank you!
you could use either asyncio.run() or loop.run_until_complete() so for your example it would be
from telethon import TelegramClient, sync
import asyncio
async def msgtelegram(entity, msg,api_id=xxx, api_hash='xx'):
client = TelegramClient('Session', api_id, api_hash)
await client.start()
if not await client.is_user_authorized():
await client.sign_in('xxx')
await client.send_message(entity, msg)
await client.disconnect()
def func():
try:
print('hello!')
except:
asyncio.run(msgtelegram(entity, msg))
This is the code:
import asyncio
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = ".")
Token=""
#client.command()
async def react(ctx):
message = await ctx.send("Test")
await message.add_reaction("<💯>")
await message.add_reaction("<👍>")
user=ctx.message.author
def check(reaction, user):
user == ctx.message.author and str(message.emoji) == '💯'
try:
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await channel.send('💯')
else:
await channel.send('👍')
client.run(Token)
The problem is that I always get an error "'await' outside async function", and the a of "reaction, user = a" get highlighted. Thank you for any help.