An error occurred when trying to async def discord.py without a command. How to perform async def? - discord

How do I perform functions without a command and why do I get this error?
from discord.ext import commands
import json
import discord
import asyncio
import pathlib
from pathlib import Path
client = discord.Client(command_prefix="!", intents=discord.Intents.all())
dir_path = pathlib.Path.cwd()
path_class_components = Path(dir_path, 'class_app', 'class_components')
path_class_components = str(path_class_components).replace("\class_wark\class_app","")+"\config.json"
config = json.load(open(path_class_components, 'r'))
async def my_background_task():
await client.wait_until_ready()
counter = 0
channel = client.get_channel(id=970589128355905539) # replace with channel_id
while not client.is_closed():
counter += 1
await channel.send(f"{counter}")
await asyncio.sleep(60)
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.loop.create_task(my_background_task())
client.run(config['token'])
gives me an error... how do I fix it or what code should I use I don't understand at all)
Traceback (most recent call last): File "C:\Users\Monik\PycharmProjects\DiscordBuy\class_app\class_wark\class_requests.py", line 36, in <module> client.loop.create_task(my_background_task()) File "C:\Users\Monik\PycharmProjects\DiscordBuy\venv\lib\site-packages\discord\client.py", line 108, in __getattr__ raise AttributeError(msg) AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook

Tasks are a great way to have functions/tasks executing every X period of time. Have a look at the docs and give them a go - shouldn't be too tricky to implement for your use case.

Thank you very much #ESloman , after reading the documentation a little and breaking my head, something came out
from discord.ext import tasks, commands
index = 0
def cog_unload(self):
self.printer.cancel()
#tasks.loop(seconds=1.0)
async def printer():
global index
print(index)
index += 1
#client.event
async def on_ready():
await printer.start()
client.run(config['token'])

Related

Discord.py bot not running

I am working on a bot and for some reason its giving me the error code of
Traceback (most recent call last):
File "main.py", line 7, in <module>
bot = commands.Bot(command_prefix='?')
TypeError: __init__() missing 1 required keyword-only argument: 'intents'
I have no idea why it isn't working I tried re-doing my code from the discord command docs. My current code is
import os
import discord
from discord.ext import commands
from replit import db
TOKEN = os.environ['TOKEN']
bot = commands.Bot(command_prefix='?')
client = discord.Client()
#bot.command()
async def echo(ctx):
await ctx.send("Welcome " + ctx.message.author.mention)
await ctx.send("Do ?commands to see all the commands")
db["money-" + ctx.message.author.id] = "0"
db["xp-" + ctx.message.author.id] = "0"
db["started-" + ctx.message.author.id] = "1"
#bot.command()
async def commands(ctx):
started = db["started-" + ctx.message.author.id]
if started == 1:
await ctx.send("--------------------")
await ctx.send("Command list")
await ctx.send("--------------------")
await ctx.send("?commands")
await ctx.send("Opens this menu")
await ctx.send("--------------------")
else:
await ctx.send("You havent ran ?start yet!")
bot.run(TOKEN)
Again I don't know much about error codes.
You need to tell which intents you want to use.
If you want to use every intent for example you have to write
bot = commands.Bot(command_prefix='?', intents = discord.Intents.all())
on line 7.
You can enable your intents on https://discord.com/developers/application choose your application and then choose Bot. If you want to use all Intents, you have to enable everything under Private Gateway Intents in order to work properly.

SyntaxError: 'await' outside async function discord.py

import discord.ext
import discord
from discord.ext import commands
from discord.ext import tasks
from keep_alive import keep_alive
import os
import schedule
client = discord.Client()
client = commands.Bot(command_prefix="")
channel_id = 927272717227528262
channel = client.get_channel(channel_id)
#tasks.loop(seconds=1.0)
#client.event
async def on_message(message):
if message.author == client.user:
return
def job2():
await message.channel.send("message")
schedule.every(10).seconds.do(job2)
while True:
schedule.run_pending()
time.sleep(0)
keep_alive()
client.run(os.getenv('TOKEN'))
Every time I run it I get :
SyntaxError: 'await' outside async function
I am also having the issue where message is undefined the definition of job2 even though it was just defined in the line above.
You should probably be using discord.ext.tasks. Async functions aren't really supported by schedule.
In fact, your bot can never run because your schedule.run_pending() in the infinite loop will never end.
In order to keep your message there you'll need to put it in a global of some type.
the_message = None
#tasks.loop(seconds=1.0)
#client.event
async def on_message(message):
global the_message
if message.author == client.user:
return
the_message = message
async def job2():
if the_message is None:
return
await the_message.channel.send("message")
#tasks.loop(seconds=10.0) # you can do other things like `minutes=5` or `hours=1.75`
async def my_task():
await client.wait_until_ready()
await job2()
my_task.start()
# then the bot runs fine after
keep_alive()
client.run(os.getenv('TOKEN'))
Be careful that this might run before your client is not ready and initializing. You may also want to check wait_until_ready if you're going to do anything with the API, like in your case. You can also find other examples here.
await is used in asynchronous functions to wait for the function to do its thing. However, you have used it in a synchronous function (def job2)
message is not a variable. message is the parameter of the on_message function. A parameter can only be used in the function it is provided to.
Hope this answered your question.

Extentions and Cogs not working in discord.py v2

I am trying to get export my troll commands in a discord bot i run to a new file, using cogs and extensions. However, the commands do not register, and I'm not sure why. I'll send the code here. (just ignore the weird function launch, it makes more sense when you look at the bot entirely but its spread thought 2k lines. )
#bot.py
import os
import sys
import time
import datetime
import discord
from discord.ext.commands import Bot
from discord import Intents
import assets
import role_counter
from discord.ext import commands
import discord.ext.commands
from dotenv import load_dotenv
import git_push
import merit_config
import trolls
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
TOKEN_TEST = os.getenv('DISCORD_TOKEN_TEST')
GUILD = os.getenv('DISCORD_GUILD')
cogs = ['cogs.trolls']
def startup(START):
global LAUNCH
global bot
if START == TOKEN:
intents = Intents.all()
bot = commands.Bot(intents=intents, command_prefix='.')
bot.remove_command('help')
LAUNCH = TOKEN
startup(TOKEN)
initial_extensions = ['cogs.trolls']
if __name__ == '__main__':
for extension in initial_extensions:
bot.load_extension(extension)
def main():
while True:
bot.run(LAUNCH)
#trolls.py
import assets
from discord.ext import commands
class troll_commands(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def troll(self, ctx):
if ctx.channel.id == '936902313589764146' or '939028644175699968':
await ctx.send(f"```{assets.troll_command()}```")
await self.bot.process_commands()
def setup(bot):
bot.add_cog(troll_commands(bot))
I've mirrored every example i can find, it just isn't working and idk why. If I'm missing some code to reporodce please just tell me, ill edit this post.
It depends on the version you're currently using but as you're having issues, you need to clarify what sort of error you're getting.
If you're using V2 then you do need to use async for the majority of your code now, here's a migration guide if you would like to take a look: https://discordpy.readthedocs.io/en/stable/migrating.html.
The main areas that you need to fix are:
if __name__ == '__main__':
for extension in initial_extensions:
bot.load_extension(extension) # you need to await this
def main(): # you aren't ever calling main
while True:
bot.run(LAUNCH)
and
def setup(bot): # needs to be async
bot.add_cog(troll_commands(bot)) # needs to be awaited
There are some other things you should reconsider like global vars but this should work for now.
You have to use async and await to be able to add a cog.
You have to async and await the extension loading and running the bot
await bot.load_extension(extension)
async def setup(bot):
await bot.add_cog(Command(bot))

'Member' object has no attribute 'hasPermission'

i wanted to make a bot to discord for delete messages easly. it works 3 months ago but now i got an error " 'Member' object has no attribute 'hasPermission' ". thanks for everyone to share opinion. have a nice day.
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
bot = commands.Bot(command_prefix = 'botcuk')
#bot.event
async def on_ready():
await bot.change_presence(activity=discord.Streaming(name="admin biseyler deniyor", url='https://www.youtube.com/watch?v=fw7L7ZO4z_A'))
if message.content.startswith('botcuksil'):
if (message.author.hasPermission('MANAGE_MESSAGES')):
args = message.content.split(' ')
if len(args) == 2:
if args[1].isdigit():
count = int(args[1]) + 1
deleted = await message.channel.purge(limit = count)
await message.channel.send('{} mesaj silindi'.format(len(deleted)-1))
It is throwing 'Member' object has no attribute 'hasPermission' this error because 'Member' does not have an attribute named 'hasPermission'. To fix your problem, I have re-written your code and also given some explanation below the code:
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
bot = commands.Bot(command_prefix = 'botcuk')
#bot.event
async def on_ready():
await bot.change_presence(activity=discord.Streaming(name="admin biseyler deniyor", url='https://www.youtube.com/watch?v=fw7L7ZO4z_A'))
#client.event # we need to add and check for a client event
async def on_message(): # we need to execute the command when we recieve an message so we define a function called 'async def on_message():'
if message.content.startswith('botcuksil'):
if message.author.guild_permissions.manage_messages: # we need 'author.guild_permissions.(permission)' intead of 'if (message.author.hasPermission('MANAGE_MESSAGES'))'
args = message.content.split(' ')
if len(args) == 2:
if args[1].isdigit():
count = int(args[1]) + 1
deleted = await message.channel.purge(limit = count)
await message.channel.send('{} mesaj silindi'.format(len(deleted)-1))
I have not tested this yet, but according to me, your problem: 'Member' object has no attribute 'hasPermission' should be solved.
What you have done was message.author.hasPermission('MANAGE_MESSAGES') but message.author has no attribute like hasPermission.
Summary of what I have done:
I have added a client event (#client.event) and an async function on_message().
What it does is it checks if it is getting an message or not. If it detects a new message in any of the servers it is invited to, it triggers the code in on_message().
As I said: What you have done was message.author.hasPermission('MANAGE_MESSAGES') but message.author has no attribute like hasPermission.
Instead of writing that, we can use message.author.guild_permissions.manage_messages. It checks if the message author's server's permissions include "manage_messages". Hope my solution fixes your problem.
Always happy to help!
-sqd mountains

discord.py wikipedia search command does not reply

When I try to run my cog it gives an error "No value for argument 'arg' in function call'. Can someone help please?
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
import os
import datetime
import random
import wikipedia
class wiki(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.Cog.listener()
async def on_ready(self):
print("Wikipedia Cog has been loaded\n-----")
#commands.command()
async def wiki(self,ctx,word):
def viki_sum(self,arg):
definition = wikipedia.summary(arg,sentences=3,chars=1000)
return definition
embed = discord.Embed(title="***Wiki'de Bulduklarım:***",description=viki_sum(word))
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(wiki(bot))```
Hello and welcome to Stack Overflow!
It seems that the error you are getting comes from this section of the code:
#commands.command()
async def wiki(self, ctx, word):
def viki_sum(self, arg):
definition = wikipedia.summary(arg, sentences=3, chars=1000)
return definition
The viki_sum function is a nested function. Even though its enclosing function is a class method and requires using self as the first argument, any nested functions do not require that argument.
So, to overcome the error, you need to remove the self argument from the viki_sum function.
Best of luck!

Resources