#discord-bots
1 messages ยท Page 148 of 1
im asking where you're getting that warn id from
it would be helpful if you sent the code
the full code for the View or whatever it is
# Why i cannot connect to channel ? pls help, write in class extends discord cog
@commands.command(name="join")
async def join(self, ctx):
channel = ctx.author.voice.channel
voice = get(self.client.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.move_to(channel)
else:
voice = await channel.connect()
What's the problem exactly
Thanksss
voice = get(self.client.voice_clients, guild=ctx.guild) -> ctx.voice_client btw
and you should also check if channel is None or not
that right?
channel = ctx.author.voice.channel
if channel is None:
await ctx.send("You are not connected to a voice channel")
return
voice = await channel.connect()
not work
this full function
@commands.command()
async def p(self, ctx: commands.Context):
if ctx.author.voice is None:
await ctx.send("You are not connected to a voice channel")
return
channel = ctx.author.voice.channel
if channel is None:
await ctx.send("You are not connected to a voice channel")
return
voice = await channel.connect()
#
voice.play(discord.FFmpegPCMAudio(executable="/asset/ffmpeg/ffmpeg.exe", source="/song.mp3"), after=lambda e: print('done', e))
voice.source.volume = 1
and you're not getting any errors? Do you have an error handler?
no err
no, but ```py
voice = await channel.connect()
print(f"voice: {voice}")
no have voice
i must install this discord.py[voice] ???
yes
oh, that work ๐
bruv
Give pic of the command where u used this class
warn_id is required
view=EditWarn(warn_id) u have to call this
Does anyone know what he is talking about?
He said "just normal ftp and ssh"
to do what
make bot's requests faster
We have the same bot my bot take 10s for a request and his take only 0.6s
ftp and ssh are things that connect you to other machine, idk what he's talking about
btw why you would want to make requests faster, if you're doing everything right you shouldn't take 10s
because its slow and I want to do multiple requests
def after_song(err):
try :
if len(queue) > 0:
next_song = url_queue.pop(0)
queue.pop(0)
song_manager = Song()
_video_title = song_manager.do_both(next_song) #downloads song and returns video_title
voice.play(discord.FFmpegPCMAudio("song.mp3"), after=after_song)
else :
url_queue.pop(0)
queue.pop(0)
return
except IndexError :
pass
voice.play(discord.FFmpegPCMAudio("song.mp3"), after=after_song)
should i use after to call the next song??
Is this good for my program?
and, ... one bot can run multi voice channel ?
hi, hello
Is this your code?
no, but it like my code
import discord
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.message_content = True
#prefix for commands
rijalbot = commands.Bot(command_prefix='!',intents=intents,activity=discord.Game(name="!rijalhelp"))
#commands
@rijalbot.command()
async def rijalhelp(ctx):
await ctx.channel.send("")
@rijalbot.event
async def on_message():
if message.content.startswith("!rijal"):
@rijalbot.event
async def on_ready():
print("RijalBot online")
TOKEN = ''
rijalbot.run(TOKEN)```
Getting "unresolved reference 'message'"
async def on_message(message)
Ah
Thanks
Show full code
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
its it working fine but its not giving response
it says interaction failed on discord without any errors in terminal
can someone help?
select.values is a list
if select.values[0] or etc
As catgal said
Also u can use
await interaction.response.defer(thinking=True) xd
import discord
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.message_content = True
#prefix for commands
rijalbot = commands.Bot(command_prefix='!',intents=intents,activity=discord.Game(name="!rijalhelp"))
#commands
@rijalbot.event
async def on_message(message):
unreliable = ["Mufaddal b. Umar"]
if message.content.startswith("!rijal"):
if str(message) in unreliable:
await ctx.send("This hadith is Da'if")
@rijalbot.command()
async def rijalhelp(ctx):
await ctx.send()
@rijalbot.event
async def on_ready():
print("RijalBot online")
TOKEN = ''
rijalbot.run(TOKEN)```
Getting an unresolved reference 'ctx'
No traceback, because the command itself doesnt run
Bro
message.channel.send it will be
Not ctx.send, ctx use for in prefix commamds
Did i even check docs?
I forgor
Now theres no errors, but when I type "!rijal" then the string in the list, nothing happens
if str(message.content)
Still nothing
What did u type?
Nvm
It will be
if unreliable in str(message.content):
Xd
import discord
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.message_content = True
#prefix for commands
rijalbot = commands.Bot(command_prefix='!',intents=intents,activity=discord.Game(name="!rijalhelp"))
#commands
@rijalbot.command()
async def rijalhelp(ctx):
await ctx.send()
@rijalbot.command()
async def rijal(ctx):
unreliable = ["Mufaddal b. Umar"]
if str(ctx.content) in unreliable:
await ctx.send("This hadith is Da'if")
@rijalbot.event
async def on_ready():
print("RijalBot online")
TOKEN = ''
rijalbot.run(TOKEN)```
ERROR discord.ext.commands.bot Ignoring exception in command rijal
Traceback (most recent call last):
File "C:\Users\intel\Desktop\rijalbot\venv\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\intel\Desktop\rijalbot\main.py", line 20, in rijal
if unreliable in str(message.content):
AttributeError: 'Context' object has no attribute 'content'
The above exception was the direct cause of the following exception:
ctx.message.content
No error, now, but no message is being sent
if you use ctx.message.content you take all prefix or anything user type
exp: !text 123
you take!text 123
u can change function like this:
@rijalbot.command()
async def rijal(ctx, name: str):
unreliable = ["Mufaddal b. Umar"]
if name in unreliable:
await ctx.send("This hadith is Da'if")
@rijalbot.command()
async def rijal(ctx):
unreliable = []
if str(ctx.message.content) in unreliable:
return
await ctx.send()
elif:
await ctx.send("e")```
Statement expected, found Py:ELIF_KEYWORD
learn basic python before making discord bots
lol
hey all im struggling on how to implement buttons, instead of typing a command to run a chunk of code e.g. !newchannel to make a new channel, how can i get it so its a button instead that runs the code?
@discord.ui.button(label="Button",style=discord.ButtonStyle.gray)
async def gray_button(self,button:discord.ui.Button,interaction:discord.Interaction):
await interaction.response.edit_message(content=f"This is an edited button response!")
``` I get this error with it:
File "main.py", line 37, in gray_button
await interaction.response.edit_message(content=f"This is an edited button response!")
AttributeError: 'Button' object has no attribute 'response' ```
Swap the button and interaction position in the callback argument
oh thank you it worked lol
@client.tree.command(name = "test")
AttributeError: 'Bot' object has no attribute 'tree'
@client.tree.command(name = "test")
async def test(interaction: discord.Interaction):
await interaction.response.send_message(content = "this msg has a button on it", view = TestButtons())```
not sure why i cant use @client.tree.command anymore
has it changed?
Are you subclassing the bot obj
yh
Can you show the code
import discord
from discord.ext import commands
from discord.ui import Button, View, button
from discord.interactions import Interaction
intents = discord.Intents.all()
client = commands.Bot(command_prefix = '!', help_command=None, intents=intents)
class TestButtons(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label = "TEST")
async def test(self, interaction: discord.Interaction, Button: discord.ui.Button):
pass
@client.tree.command(name = "test")
async def test(interaction: discord.Interaction):
await interaction.response.send_message(content = "this msg has a button on it", view = TestButtons())
what library and version are you using? can you check with pip list?
the command tree only exists in discord.py 2.0, so your error would suggest you either have an alpha version of discord.py or some other library like pycord/nextcord
!d discord.interactions.Interaction ( checking path)
hm the commands.Bot should have a tree added by default
avatar_url_as changed to?
https://discordpy.readthedocs.io/en/stable/migrating.html#asset-redesign-and-changes
User.avatar_url_as(replaced byUser.avatar.replace)
btw spooky.exe thank you so much it worked
YP
how to make a avatar command with embed?
If its 0 then it should not enter the if statement
The control enters if statement, do everything but don't execute the response statement
is there a thing called on_member_join
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
how do i add a role on a event
you can use Member.add_role
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
takes Role objects as argument
i mean get the role
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
url= avatar url
what is atomic?
thanks
how can i create an event that punish a member when he adds a bot ?
i just need the event , and the member getting code
!d discord.on_integration_create
discord.on_integration_create(integration)```
Called when an integration is created.
This requires [`Intents.integrations`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.integrations "discord.Intents.integrations") to be enabled.
New in version 2.0.
The user that added this integration.
@sistanibot.command()
async def ruling(ctx):
rulings = {("a","b"): "c"}
for key in rulings:
if ctx.message.content in key:
await ctx.send(rulings.value)```
I do !ruling a, but I get no output, theres no error message, im trying to do a command where if you do !ruling a, you get the value outputted, which is c
how do i make my bot only wait for discord user ids instead of any number
just go learn python yourself
make a userselect
!d discord.ui.UserSelect
class discord.ui.UserSelect(*, custom_id=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None)```
Represents a UI select menu with a list of predefined options with the current members of the guild.
If this is sent a private message, it will only allow the user to select the client or themselves. Every selected option in a private message will resolve to a [`discord.User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
New in version 2.1.
n
no i meant wanna do a bot toghether
like we code both bruh
sure i believe u... ๐ฟ either ways this is not a place for recruitment
alr why you on bad mode
just dont care then
cant i just change the content to only check for discord user ids
or for a number with 18 digits
idc thats why i didn't go in depth wether u know python or not i checked ur messages in the server b4 thats why I dont even bother if u have sone discord bot related questions u can ask
ok just dont bother still lol
it will be more tedious coz discord recently changed the number of digits in their id u have to fetch the user to check if it's valid trust me it's easier with a userselect and less amount of code
and by using discord.ui.select it will take the id i sent to the bot and the bot will say the id back to me
UserSelect and yes their selection will be visible to u in the callback
so just yk what i want to do
i want to send a users id to my bot and then i want my bot to send the exact id i sent to the bot back in chat
and thats possible through discord.ui.select
... yes and also b4 u ask me how to do it i suggest u check the docs
if u dont get which part u can ask
discord.py 2.1+
How to use?
You can NOT filter the members, roles or channels shown.
You can set the min/max amount of options the user can or must choose using the min_values and max_values kwargs.
- Members, Roles or both:```py
import the correct class...
Only members?
from discord.ui import UserSelect
Only roles?
from discord.ui import RoleSelect
Members and roles in one?
from discord.ui import MentionableSelect
import for the decorator and callback...
from discord import ui, Interaction
using...
this example uses the UserSelect
class MyView(ui.View):
# @ui.select(cls=type_we_want, **other_things)
@ui.select(cls=UserSelect, placeholder="Select a user please!")
async def my_user_select(self, interaction: Interaction, select: UserSelect):
# handle the selected users here
# select.values is a list of User or Member objects here
# it will be a list of Role if you used RoleSelect
# it will be a list of both Role and Member/User if you used MentionableSelect
users = [
f"Name: {user.name}, ID: {user.id}"
for user in select.values
]
print(
f"{interaction.user} selected the following users:",
"\n".join(users)
)
use MyView like any other view.
these can also be subclassed like the others.
- Channels:
You can use the `ui.ChannelSelect` class, and limit the type of channels shown with the `channel_types` kwarg:```py
# All channels?
@ui.select(cls=ui.ChannelSelect, ..., ...)
# Only text channels?
@ui.select(cls=ui.ChannelSelect, ..., channel_types=[discord.ChannelType.text], ...)
# etc, channel_types takes a list of discord.ChannelType.
Docs: https://discordpy.readthedocs.io/en/latest/interactions/api.html#select-menus
isnt ui.select used for dropwdown menus
yes send that with ur response to the command
i dont want a dropdown menu tho
dont see the point of a message event in a slash command u can use a modal instead ig coz if u take from message event u will have to do a bunch of extra handling to make sure validation of the id ยฏ_(ใ)_/ยฏ
just use the UserSelect makes life easier
def check(message):
return message.author == interaction.user and message.channel == interaction.user and message.content.isdigit() and client.get_user(int(message.content))
also since check is supposed to be sync if the user is not in bot cache u have to write a few more lines to fetch the user and check
like this right
it didnt work
Why eat ๐
The error is telling what's the exact problem is 
print(groupreq)
i was hungry ๐ฅฒ
visually?
discord.ext.commands.bot Ignoring exception in command sistanifatwa
Traceback (most recent call last):
File "C:\Users\intel\Desktop\rijalbot\venv\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\intel\Desktop\rijalbot\main.py", line 20, in sistanifatwa
kyword = dict.get(key)
TypeError: descriptor 'get' for 'dict' objects doesn't apply to a 'str' object
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\intel\Desktop\rijalbot\venv\lib\site-packages\discord\ext\commands\bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\intel\Desktop\rijalbot\venv\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\intel\Desktop\rijalbot\venv\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: descriptor 'get' for 'dict' objects doesn't apply to a 'str' object
@sistanibot.command()
async def sistanifatwa(ctx,key):
rulings = {("a","b"): "c"}
kyword = dict.get(key)
if kyword is not None:
return
await ctx.send(kyword)```
Why hungry
I did !sistanifatwa a
can a tuple be a dict key?
be4 creation = add this
groupreq = groupreq['data'][0]
yessir
til
Wassup
Why do I get a feeling that u both know each other?
?
๐
@sistanibot.command()
async def sistanifatwa(ctx, *key):
rulings = {("a","b"): "c"}
kyword = rulings.get(key, None)
if kyword is None:
return
await ctx.send(kyword)```
call command like this
`prefix[command_name] a b`
how u figure that out?
He is a mind reader ๐ฟ


U r frommm....? ๐
Don't tell if personal xd
india
Nah, i want it so that if a or b is called, the value should be outputted
his name is sarth
Cul, only me is from a alien country 
sarthak to be precise
Ye i saw
@sistanibot.command()
async def sistanifatwa(ctx, key):
rulings = {"a": "c", "b": "c"}
kyword = rulings.get(key, None)
if kyword is None:
return
await ctx.send(kyword)```
call command like this
`prefix[command_name] b`
spoon feeding be like
damn
asher
Then why u feeding him, let him figure it out xd
spoon feed me im confused ;-;
idk i am in good mood
send ur command as code here
exactly
Haha
after sometime i need to go study so rn my break time 
xd
def check(message):
return message.author == interaction.user and message.channel == interaction.user and message.content.isdigit() and client.get_user(int(message.content))
msg = await client.wait_for('message', check=check)
await msg.channel.send(f'USER ID IS {msg.content}')```
Today i had my physics xm ๐๐
Tmrw is bio, so hard ahhh
its what im tryna do i said earlier
the command plz
also interaction.channel == message.channel
what do i change to this to make it work
i want to send my discord bot a users id and then for my to send that id back to me
Why u returning it tho?
thats the code u sent me
Idk ig i am just bad
def check(message):
return message.author == interaction.user and message.channel == interaction.channel and message.content.isdigit() and client.get_user(int(message.content))
msg = await client.wait_for('message', check=check)
await msg.channel.send(f'USER ID IS {msg.content}')```
for my defence i was hungry 
cant think on an empty stomach
i get distracted ๐
Sedge
the way of talking
become a psychiatrist
works ty ๐ญ
no
Ok
anyone know how i can make it so it send a random joke when no argument is specified and when a category is passed it send from this category?
@commands.command("oof")
async def joke(self, ctx, category):
randomurl = "https://api.chucknorris.io/jokes/random"
categoryurl = f"https://api.chucknorris.io/jokes/random?category={category}"
response = httpx.get(randomurl).json()["value"]
await ctx.send(response)
in the params, make category = None and in the function do
if not category:
....
okay, i now somehow get command not found issue with both (>oof and >joke)
The commands wasn't loaded
it say it was
/home/infinimonster/Documents/Privat/Python/discord-bot/main.py:15: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
try: bot.load_extension(f"Cogs.{filename[:-3]}"); print(f"{colorama.Fore.RED}[>] {colorama.Fore.GREEN}Cogs.{filename[:-3]} loaded")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
[>] Cogs.fun loaded
[>] Bot is ready!
It give this await warning but the cog still loads
It's just warning, not error(or exception)
And you should await it if you already know you have to
it's in main.py so there is no async stuff
Of course there is
HOW TO EDIT AN EMBED DESCRIPTION ?
Ok
not if i not added asnyc
but the issue is the commands not found issue
and it not seem to be cog loading issue
Because you didn't load the cog
So the commands in that cog won't be loaded

Sure
after it's already sent?
yep
i think its like
your_var = await ctx.send(embed=yourembedvar) await your_var.edit(embed=newembed)
Did you await the load extension
thats the problem
!e
from asyncio import run
async def coro():
pass
async def main():
coro()
print("owo")
run(main())
but i want to use a loop for editing , it will increase a number for the insertion
!e
print("hi")
@slate swan :white_check_mark: Your 3.10 eval job has completed with return code 0.
hi
oh
You need to await it
may i ask what it's for
giveaway

the time will be -1 in each second
you'll get rate limited
@sistanibot.command()
async def sistanifatwa(ctx,key):
rulings = {}
kyword = rulings.get(key, None)
if kyword is None:
return
await ctx.send(kyword)
elif kyword is not None:
return
await ctx.send("Not found!")
File "C:\Users\intel\Desktop\rijalbot\main.py", line 34
elif kyword is not None:
^^^^
SyntaxError: invalid syntax
that's a hard rate limit
Do you know basic Python
aah
it give me error every time
What error
RuntimeError: asyncio.run() cannot be called from a running event loop
sys:1: RuntimeWarning: coroutine 'Client.run.<locals>.runner' was never awaited
u have to make a async function for to run the client
done this
Or just load the extensions in setup_hook
async def r():
await client.run()
asyncio.run(r())```
await giveaway.edit(embed=embed.description=....
would this work ?
idk i dont use discord 2.0.0 i use pycord
!d discord.Client.run
run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., root_logger=False)```
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login").
This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.
Warning
This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
yes, my runbot function is alredy async
It's not a coroutine
im playing word bomb
How did you load the extensions
Fuck logitech g502
import colorama; colorama.init(autoreset=True)
import discord
import os, sys
import traceback
import asyncio
from discord.ext import commands
# load all cogs in the cogs folder
if __name__ == '__main__':
TOKEN = "secret"
bot = commands.Bot(command_prefix='>', self_bot=True)
async def runbot():
for filename in os.listdir("Cogs"):
if filename.endswith(".py"):
try: await bot.load_extension(f"Cogs.{filename[:-3]}"); print(f"{colorama.Fore.RED}[>] {colorama.Fore.GREEN}Cogs.{filename[:-3]} loaded")
except Exception as e: print(f'Failed to load extension {filename}', file=sys.stderr); traceback.print_exc()
try: print(f"{colorama.Fore.YELLOW}[>] {colorama.Fore.LIGHTGREEN_EX}Bot is ready!"); bot.run(TOKEN)
except discord.errors.LoginFailure: print(f"{colorama.Fore.YELLOW}[>] {colorama.Fore.LIGHTRED_EX}Improper token has been passed!")
asyncio.run(runbot())
My god
?
Just run the bot normally and set the bot's setup_hook to load extension function
Like
bot = commands.Bot(...)
async def load_ext_setup_hook():
# load the extensions here
pass
bot.setup_hook = load_ext_setup_hook
if __name__ == "__main__":
bot.run(...)
Or subclass the bot class
i now changed it to this:
asyncio.run(bot.load_extension(f"Cogs.{filename[:-3]}")); print(f"{colorama.Fore.RED}[>] {colorama.Fore.GREEN}Cogs.{filename[:-3]} loaded")
but now i got another weird issue:
discord.ext.commands.errors.ExtensionFailed: Extension 'Cogs.fun' raised an error: TypeError: object NoneType can't be used in 'await' expression
i don't want to load them manually so suggesting me to do so is not helpful, i simply want to fix the errors and then move on.
THIS is how you fix it
And it's just creating a function and setting attribute
That's it
I need code for this
examples/views/link.py lines 21 to 33
# Define a simple View that gives us a google link button.
# We take in `โquery`โ as the query that the command author requests for
class Google(discord.ui.View):
def __init__(self, query: str):
super().__init__()
# we need to quote the query string to make a valid url. Discord will raise an error if it isn't valid.
query = quote_plus(query)
url = f'https://www.google.com/search?q={query}'
# Link buttons cannot be made with the decorator
# Therefore we have to manually create one.
# We add the quoted url to the button, and add the button to the view.
self.add_item(discord.ui.Button(label='Click Here', url=url))```
ok done this now but issue is same
Then what is it
[>] Bot is ready!
/home/infinimonster/Documents/Privat/Python/discord-bot/Cogs/fun.py:16: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(FunCog(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Failed to load extension fun.py
Traceback (most recent call last):
File "/home/infinimonster/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 788, in _load_from_module_spec
await setup(self)
TypeError: object NoneType can't be used in 'await' expression
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/infinimonster/Documents/Privat/Python/discord-bot/main.py", line 15, in loadext
try: await bot.load_extension(f"Cogs.{filename[:-3]}"); print(f"{colorama.Fore.RED}[>] {colorama.Fore.GREEN}Cogs.{filename[:-3]} loaded")
File "/home/infinimonster/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 854, in load_extension
await self._load_from_module_spec(spec, name)
File "/home/infinimonster/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 793, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'Cogs.fun' raised an error: TypeError: object NoneType can't be used in 'await' expression
cd /home/infinimonster/Documents/Privat/Python/discord-bot/Cogs
You would have known the issue if you read the error
!d discord.ext.commands.Bot.add_cog
await add_cog(cog, /, *, override=False, guild=..., guilds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a โcogโ to the bot.
A cog is a class that has its own event listeners and commands.
If the cog is a [`app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group") then it is added to the botโs [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") as well.
Note
Exceptions raised inside a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog")โs [`cog_load()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.cog_load "discord.ext.commands.Cog.cog_load") method will be propagated to the caller...
add_cog is a coroutine, await it
that message also includes a second error indicating that setup() isnt an async function
Hello, one question, in this example how can you call a function without adding the parameter (ctx), I try it and it gives me an error, maybe it's something very stupid but I can't find the logic
Ok, I realized, all this is thanks to the click with the click.pass_context, I thought that maybe there would have to be something related to ctx -> commands.Context but I was wrong, thanks for your attention
yeah its just how click works, you're actually calling a Command object returned by the command() decorator and that doesnt require any arguments
The point is, what is the purpose of click?
click is a library for building command line interfaces
thanks so much
documentation: https://click.palletsprojects.com/en/8.1.x/
(its also not related to #discord-bots so this channel is a bit inappropriate for the topic)
while duree > 0:
duree = int(duree - 1)
embed = discord.Embed(title=ctx.guild.name, description=(
"**Time left: " + str(duree) + " seconds\nWinners: " + str(
winners) + "\nPrize: " + prize + "**"))
await giveaway.edit(embed=embed)
sleep(60)
if duree == 0:
await ctx.send("visca barca")
else:
continue```
error : discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'duree' referenced before assignment
i need dev for bot
If this condition isn't true, the variable won't exist
!e
def main():
if 0:
string = "owo"
else:
pass
print(string)
main()
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 9, in <module>
003 | File "<string>", line 7, in main
004 | UnboundLocalError: cannot access local variable 'string' where it is not associated with a value

yep , i fixed it
i had an error about the error name
it was 'value error' not 'index error'
!e
code
!e print('Hi')
how to get the members who reacted to a message in discord.py
How do I get the bot's avatar via interaction?
!d discord.Message.reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
!d discord.Reaction.users
async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") representing the users that have reacted to the message.
The `after` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
Changed in version 2.0: `limit` and `after` parameters are now keyword-only.
Examples
Usage...
u cant
too many people are hosting their bots on replit's datacenters so they all hit the same ratelimit
not on replit also its not cloudflare ratelimit but discord
!d discord.Interaction.client
property client```
The client that is handling this interaction.
Note that [`AutoShardedClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoShardedClient "discord.AutoShardedClient"), [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot"), and [`AutoShardedBot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.AutoShardedBot "discord.ext.commands.AutoShardedBot") are all subclasses of client.
await interaction.response.send_message is only working in the indent marked with green
its not working anywhere else
can someone tell me why?
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
indentation over curly braces anyday
huh
so it should work in the same indent as the for loop but its not
the if statement exists 
i tired but it still gave errors
hello
read up on indentations and if elif chains/blocks
am here
hello sir
it worked
i placed the response before for loop
its wasnt working after for loop
but yeah worked
ur loop is failing
if ctx.channel.id == (
):
...
# Allows bot to use @bot.command() commands along with on_message event
await client.process_commands(ctx)
See an issue here?
So is discord.py
It's got all the newest features
It does?
believe it or not most people use discord.py
I heard it was discontinued?
They also did continue
Guys can someone help me with my disscord.py bot?
!print('spam')
if name == 'main':
print('eggs')
!eprint('spam')
if name == 'main':
print('eggs')
#bot-commands and you gotta use codeblocks
!e ```py
print("Hello World!")
```
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
you gotta send some more info than "can you help"
either code, an error, or somethin else
preferably both of those lmao
Can I DM you?
i mean theres tons of people here to help but if its sensitive then ig
'Attachment' object has no attribute 'fp'
Hey @slate swan!
It looks like you tried to attach file type(s) that we do not allow (.zip). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
@ad.event
async def on_guild_join(guild):
with open(f"{guild.id}.json", "w") as f:
f.write("{}")
with open(f"{guild.id}.json", "r") as f:
guilds = json.load(f)
await saveguild(guilds, guild)
with open(f"{guild.id}.json", "w") as f:
json.dump(guilds, f, indent=4)
This wont make the file, anyone help?
If anyone needs the CTX combined with TREE COMMANDS with COGS to get official slash commands on their bot I put a sample to download just click my server profile link or DM me for any help .
with open(f"{guild.id}.json", "a") as f:
f.write("{}")
with open(f"{guild.id}.json", "w") as f:
json.dump(f, indent=4)
with open(f"{guild.id}.json", "r") as f:
guilds = json.load(f)
await saveguild(guilds, guild)
with open(f"{guild.id}.json", "w") as f:
json.dump(guilds, f, indent=4)
Please I need to complete this by today
when syncing commands, does it wipe all the permissions set in the guild settings > integrations > command > permissions
{"1048657638369525811": {"channel": "", "ad": "welcome\nto\ntest"}}
is there a way to make this multi line?
It does not
I did
Show me
I meant the code lol
@winged linden is there a way to set those permissions in discord.py?
Just set them in the intergrations tab
@ad.tree.command(name='ad', description='Set your ad to advertise!')
@app_commands.describe(adv = 'Put your ad!')
async def advertise(ctx: discord.Interaction, adv: str):
with open(f"{ctx.guild.id}.json", "r") as f:
guilds = json.load(f)
guilds[f'{ctx.guild.id}']['ad'] = adv
with open(f"{ctx.guild.id}.json", "w") as f:
json.dump(guilds, f, indent=4)
I do not know of a way to set them in discord py
Where fo you interaction.response
none
Probably needed to save
yet
How is the message being posted
wym?
@ad.command()
async def myad(ctx):
with open(f"{ctx.guild.id}.json", "r") as f:
guilds = json.load(f)
ad = guilds[f'{ctx.guild.id}']['ad']
await ctx.send(ad)
What do you want it to send
F
Put in code blocks
split lines for \n in the json
Give me the output you want and the output you get
yeah i forgot to press shift when pressing enter
Its all g
{
"1048657638369525811": {
"channel": "",
"ad": "hi\n__guys__ crazy innit"
}
}
output:
hi
guys crazy innit
I assume the top parameter is the guild Id?
channel id
It sent this whole ting?
What does it post when you run it
Then in a separate message tell me what you want it to send
basically I want \n to do its job as its not doing that
its sending hi\nguys
not
hi
guys
Print what is being loaded from json
b = Button(label=f"Apply for Staff",style=discord.ButtonStyle.green)
async def form(interaction : discord.Interaction):
await interaction.response.send_modal(Feedback())
b.callback = form
view = View(timeout=None)
view.add_item(b)
await ctx.send(f"Click on this button to apply for Staff", view=view)
So I just have this code where it should send a Modal and every time I press the button I get this error: raise ValueError('could not find open space for item') ValueError: could not find open space for item I never got it before and tried to google it but couldnt find anything
My output is ```
Baller
Is Good
!e print("Baller \n Is Good")
@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Baller
002 | Is Good
iphone user spotted
Lol
I was like whot are those.
โ
What is __guys__
!charinfo โ
\u201c : LEFT DOUBLE QUOTATION MARK - โ
:3
Just an iphone user trying to help ๐ญ
Are you making AoC puzzles?
Hm..?
advent of code
nah bruh IO just fixed it
ad = guilds[f'{ctx.guild.id}']['ad']
ad = ad.replace('\\n', '\n')
Only Eric makes puzzles
Lol
I have a puzzle idea! Can I send it to you? Please don't. Because of legal issues like copyright and attribution, I don't accept puzzle ideas, and I won't even read your email if it looks like one just in case I use parts of it by accident.
https://adventofcode.com/2022/about
LOL
Bro defo got sued
i am however making an AoC tool: https://github.com/Robin5605/aoc-template :P
Might do one next year with the template
Or ill somehow make an easter event
Still working out a finks kinks in the codebase
Traceback (most recent call last):
File "main.py", line 39, in <module>
@ad.command()
AttributeError: 'Command' object has no attribute 'command'
@ad.command()
Show line 39
Wait
.
This is in a slash command
not anymore
Hasn't chat in 2 years dw
ad = commands.Bot(command_prefix='--', intents=discord.Intents.all())
Command object
?
Gonna need more info chief since ad isn't a Bot.
Then why is the TB saying it's a Command object?
from discord.ext import commands
Should fix it no?
Honestly cannot say without more references to code.
import discord
from discord.ext import commands
import json
from discord import app_commands
ad = commands.Bot(command_prefix='!a', intents=discord.Intents.all())
async def saveguild(guilds, guild):
if not f'{guild.id}' in guilds:
guilds[f'{guild.id}'] = {}
guilds[f'{guild.id}']['channel'] = ''
guilds[f'{guild.id}']['ad'] = ''
@ad.event
async def on_ready():
synced = await ad.tree.sync()
print(f"Logged in as {ad.user}.\nSynced {len(synced)} commands.")
@ad.event
async def on_guild_join(guild):
with open(f"{guild.id}.json", "a") as f:
f.write("{}")
with open(f"{guild.id}.json", "r") as f:
guilds = json.load(f)
await saveguild(guilds, guild)
with open(f"{guild.id}.json", "w") as f:
json.dump(guilds, f, indent=4)
@ad.command()
async def ad(ctx, *, adv):
with open(f"{ctx.guild.id}.json", "r") as f:
guilds = json.load(f)
guilds[f'{ctx.guild.id}']['ad'] = adv
with open(f"{ctx.guild.id}.json", "w") as f:
json.dump(guilds, f, indent=4)
adv = adv.replace('\\n', '\n')
await ctx.author.send(f"**Set your ad to**:\n{adv}")
@ad.command()
async def myad(ctx):
with open(f"{ctx.guild.id}.json", "r") as f:
guilds = json.load(f)
ad = guilds[f'{ctx.guild.id}']['ad']
ad = ad.replace('\\n', '\n')
await ctx.author.send(ad)
Or a more clear explanation why ad is a Command object.
I cant lie ad is not the best name for your bot
its the same as client or bot
Also are you making a json for each guild?

is there anyway to delete messages in dm channel
yea
Why not just put them in one json and loop through them
idk how
also is there a way to check if the channel id is in the same guild?
Just make a while loop that constantly ads 1 to a variable per second and then display the variables value when someone runs the command
like
--setchannel id
and it will see if the id provided is a channel in the same guild the command was run
if channel.guild?
I think that wokrs
Or a datbase...
ยฏ_(ใ)_/ยฏ
How do I create an unban command in Discord.py? Here's mine:
@commands.command()
@commands.has_permissions(ban_members=True)
async def unban(self, ctx, member: discord.Member, *, reason = "not specified"):
await member.unban()
await ctx.send(f"Unbanned: {member}")
could you point me in the write direction?
if channel.guild.id ==
How do I get the member ID of a Discord member as an argument?
Assuming channel is a textchannel
Arenโt you trying to unban a user whos not a member
if channel.id in [c.id for c in guild.channels]:
...
If they are banned they arenโt a member anymore
Me when spoonfeed 
I am trying to unban a user who got banned in a server before
Whys it called unban
Removes the ban of a member I think...
Yeah but as Fiery mentioned you can't typehint a Member that isn't in your guild.
So if someone gets banned in a different server you want to un ban them from a specific server?
I am trying to unban a banned member in my server with an unban command
Should I use guild.unban()?
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 60, in setchannel
if ctx.guild.id != id.guild:
AttributeError: 'int' object has no attribute 'guild'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'guild'
if ctx.guild.id != id.guild:
what is id.guild
channel id
What
id=0
--setchannel 1048657953948962888
Your comparing guilds not channels
If you have the channel id then you will need to get the guild of the channel
Or get the channel that your looking for in the original guild
Little confused on your goal
You need to store their id when they are banned
I think
Ok thanks
banned_users = await ctx.guild.bans()
@commands.command()
@commands.has_permissions(ban_members=True)
async def unban(self, ctx: Context, user: discord.User, *, reason: str = "Not specified.") -> None:
try:
await ctx.guild.unban(user, reason=reason)
message = f"Unbanned: {user}"
except (NotFound, Forbidden, HTTPException):
message = f"Couldn't unban: {user}"
await ctx.send(message)
Will tell you whos banned
Bro spoonfed for me
You aren't asking questions :3
I was going to spoonfeed code to him LOL
lel
can you spoonfeed me a robot that can send me to the moon k thz
I heard about this on Stack Overflow
If you can avoid it, do it.
Not stackoverflow but that code.
Depending on the size await ctx.guild.bans() can be a heavy request.
Thanks for the help Fiery and Pandabweer
Alwayss happy to help as much as I can
It will also be more in the style of ```py
async for ... in bans(*, limit=1000, before=..., after=...):
...
Yeah but the limit would mean if they have more then 1000 bans
Some people arenโt getting unbanned lol
But your code solves the issue so its chilling
so close to finishing this i think
with open(f"{guildid}.json", "r+") as f:
guilds = json.load(f)
channel2 = guilds[f'{guildid}']['channel']
ad2 = guilds[f'{guildid}']['ad']
channel = guilds[f'{ctx.guild.id}']['channel']
ad = guilds[f'{ctx.guild.id}']['ad']
if channel2 or ad2 or channel or ad == "":
await ctx.send("Cant partner as there configs arent setup.")
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 101, in partner
channel = guilds[f'{ctx.guild.id}']['channel']
KeyError: '1048657638369525811'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: '1048657638369525811'
{
"1048657638369525811": {
"channel": "1048657953948962888",
"ad": "test"
}
}
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 109, in partner
await channel.send(ad)
AttributeError: 'NoneType' object has no attribute 'send'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'
Are you sure its a integer
i got it
else:
channel = bot.get_channel(channel2)
await channel.send(ad)
channel = bot.get_channel(channel)
await channel.send(ad2)
Check that channel2 is an integer
ill int them
Where do you get the value of channel2 btw
omg it works
channel2 = int(channel2)
channel = int(channel)
channel2 = bot.get_channel(channel2)
await channel2.send(ad)
channel = bot.get_channel(channel)
await channel.send(ad2)
hey yoo
how I can fix this?
@winged linden
TOKEN = โyourtokenโ
client.run(TOKEN)
idk what your doing with process.env
there's nothing wrong. It's just saying that you aren't using the imported package
Simpler
Just dont share your source with nobody you dont trust no?
I guess
I local host when I test so
The same problem
Reverse your change i was wrong
but I'm trying to, and my code doesn't work
for example, this command doesn't work and idk why
traceback?
command_prefix, not commands_prefix
yeah
I check the log and doesn't appear nothing :/
The same problem
well then you have to either check any error handlers, or elaborate on what you mean with "code doesn't work"
Im on mobile
Dos it still say this errror?
seconds = str(x % 60)
How can I remove the decimal places on this, i tried math but it didnt work
Yes
Did you save your work
like, I have that command, for example, and just when I write on discord, nothing happens :/
And rexecute
try
rand.randint(1, 20)
that shouldn't return decimals?
Thats what I was thinking
send your entire code please, and obfuscate the token if its visible
That will give minutes not seconds
either way
So whh is variable named seconds
Ahhh why
x = error.retry_after
minutes = str(x // 60)
seconds = str(x % 60)
await ctx.send(f"Minutes: {minutes} | Seconds: {seconds}")
none of those should return a decimal value
import discord
from discord import player
from discord.ext import commands
from discord.ext import tasks
from mcstatus import MinecraftServer
import asyncio
import random
token = 'oya oya'
cliente = commands.Bot(command_prefix= '-', case_insensitive = True)
server = MinecraftServer.lookup("188.80.167.41")
@tasks.loop(seconds=40)
async def changepresence():
global x
game = iter(
[f"em Alcanena Shenanigans!", " no servidor de Minecraft!", " | Em desenvolvimento!", " | -help"])
for x in range(random.randint(1, 4)):
x = next(game)
await cliente.change_presence(activity=discord.Game(name=x))
@cliente.event
async def on_ready():
print('Entramos como {0.user}' .format(cliente))
changepresence.start()
@cliente.command()
async def players(ctx):
query = server.query()
if status.players.online > 0:
embed = discord.Embed(title = 'Status', description = f'Players Online: {status.players.online}', colour = 2523174)
embed.set_author(name = ctx.message.author.name, icon_url = ctx.message.author.avatar_url)
else:
embed = discord.Embed(title = 'Status', description = f'Players Online: {status.players.online}\nThe server has the following players online: {query.players.names}', colour = 2523174)
embed.set_author(name = ctx.message.author.name, icon_url = ctx.message.author.avatar_url)
await ctx.send(embed = embed)
@cliente.command()
async def status(ctx):
status = server.status()
query = server.query()
latency = server.ping()
embed = discord.Embed(title = 'Status', description = f'Players Online: {status.players.online}\nNicks: {query.players.names}\nPing: {latency}', colour = 2523174)
embed.set_author(name = ctx.message.author.name, icon_url = ctx.message.author.avatar_url)
await ctx.send(embed = embed)
cliente.run(token)```
What is x
Oh
its in the code
^
What was the issue
don't dynamically change presences and you have to have message content intents enabled
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
x = error.retry_after
x = int(x)
minutes = x // 60
seconds = x % 60
minutes = int(minutes)
seconds = int(seconds)
await ctx.send(f"Please wait {minutes} minutes and {seconds}{'' if seconds == 1 else 's'}")
idk i int it
Oh bruh
hmm, but before, this code was working fine..., I'll see this
ty for your help :)
for that I was updating the discordpy's package and this...
upgraded the requirements file and doesn't exist
@fading marlin
how do I open original message with videos
(I am very very very new to all of this, so I apologize if I act as such by not knowing what you may be saying at times, and if this is the wrong place for this.)
I have been stuck for a couple days now just trying to bring my bot online for Discord. I keep returning this error message for "Improper Token has been passed" when I run the module. (Picture one)
I have been using the Bot Token under the Bots tab in the Application. I've also reset the token numerous times, updating my code with the new token every time.
I have completely deleted the application all together, created a new one, created a new bot and even then it doesn't give me the option to "Copy" at the very start, I always have to Reset the token before being able to copy it. (Picture two) (NEWLY created bot)
Is there something that I did that could have caused this issue?
Can u show us your code?
It would be better for you to use command instead of using on_message
This is the example from the Github page of discord.py
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='>', intents=intents)
@bot.command()
async def ping(ctx):
await ctx.send('pong')
bot.run('token')
Ok, so I copy and pasted that, and put my token in but still got the same error message lol. I might be in over my head maybe
Yes without the < >
yo how do i stop tasks from restarting when i reload the cog
I think every time i reload the cog it adds a new task loop
you cancel the task once you unload the cog
can i just pause the task?
sure
though you'd have to keep track of the cog instance for it not to start once you reload it
like on unload, pause the task
and then I'd have to track the task to start it up again on reload? and also stop a new one from starting on reload
yup
how do i access all running tasks?
I don't think that's stored anywhere, pretty sure you have to save that yourself
ah okay. if I have multiple running in the background, would I check it someone in my ide?
wdym?
like how would I check the loops that have built up if I haven't been stopping them on cog unload
they aren't stored anywhere apparently
then where would they be running?
discord/ext/tasks/__init__.py line 398
self._task = asyncio.create_task(self._loop(*args, **kwargs))```
What should I do if I can't find the FFmpeg .zip file this person is using in the tutorial I'm watching? It seems to be older than what I can find on github
I've been there, when I click on BtbN it takes me to github to download from a list of zip files. But the Auto-Build thread is from early Feb 2021, and I can't go past late Feb 2021 lol
(I'm brand spankin new to this, I'm just super excited I got my bot to join my vc lmao)
I tried to test the ban command on an alt account with my Discord.py bot. I removed the ban on my alt account. I cannot invite my alt account back to my test server. How do I fix this issue?
I'm assuming you tried going to Discord's "Moderation" settings in the server settings?
Yes
The audit log says I did remove the ban.
hmm
its usually a slow api thing
typically a one time vpn will help
enable, rejoin, then disable
I don't want to violate Discord TOS.
I will try again the next day...
does it really violate TOS if you own the server?
Probably not...
no
That server is a private test server
only when you are bypassing something that isnt yours would it be technically breaking tos
should be able to find the exe's in the bin file
โค๏ธ
def is_owner(self):
def predicate(self, ctx):
return ctx.author.id == self.owner
return commands.check(predicate)```
i have taken a decently long break from discord.py, and im attempting to create a decorator, am i making an obvious mistake here?
That was my guess too.
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 245, in setup
guilds = json.load(f)
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/json/__init__.py", line 293, in load
return loads(fp.read(),
io.UnsupportedOperation: not readable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnsupportedOperation: not readable
@bot.command()
async def setup(ctx):
try:
f = open(f"{ctx.guild.id}.json", "r")
except:
f = open(f"{ctx.guild.id}.json", "a")
f.write("{}")
guilds = json.load(f)
await saveguild(guilds, ctx.guild)
with open(f"{ctx.guild.id}.json") as f:
json.dump(guilds, ctx.guild)
"not readable"
for guild in bot.guilds:
if guild.name != "Advertising Bot":
count += 1
embed.description += f"{count} - {guild.name} - {guild.id}\n"
await ctx.send(embed=embed)
i think i indented wrong
yes, move the await ctx.send out of that loop
yea got it
perfect
how can i crerate a on_message event with reply to each message ?
@bot.event
async def on_message(message):
await message.reply("yea")
lol damn nvm
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 284, in addword
json.dump(guilds, ctx.guild)
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/json/__init__.py", line 180, in dump
fp.write(chunk)
AttributeError: 'Guild' object has no attribute 'write'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'write'
my mind damn
@bot.command()
async def addword(ctx, *, word):
with open(f"{ctx.guild.id}.json", "r") as f:
guilds = json.load(f)
format = f'{word}, '
guilds[f'{ctx.guild.id}']['words'] += format
with open(f"{ctx.guild.id}.json", "w") as f:
json.dump(guilds, ctx.guild)
how can i store embeds in db ?
u can store the data for title and desc
stuff like that
idk about just one var for the whole thing
ohhhk k thanks
maybe try in where your storing it
this = discord.Embed()
then load this and make it a var
then await ctx.send(embed=var)
embed in the end is just a dictionary so store it like that
Back again with another dumb question. The tutorial I've been following ended up at a point where the person moved from discord.py to Nextcord. Do I HAVE to move away from discord.py to add my bot to the slash commands list? I'd also like to create buttons for my bot so I can play a specific audio file with the click of a button
no
!d json.dump
json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* as a JSON formatted stream to *fp* (a `.write()`-supporting [file-like object](https://docs.python.org/3/glossary.html#term-file-like-object)) using this [conversion table](https://docs.python.org/3/library/json.html#py-to-json-table).
If *skipkeys* is true (default: `False`), then dict keys that are not of a basic type ([`str`](https://docs.python.org/3/library/stdtypes.html#str "str"), [`int`](https://docs.python.org/3/library/functions.html#int "int"), [`float`](https://docs.python.org/3/library/functions.html#float "float"), [`bool`](https://docs.python.org/3/library/functions.html#bool "bool"), `None`) will be skipped instead of raising a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError").
The [`json`](https://docs.python.org/3/library/json.html#module-json "json: Encode and decode the JSON format.") module always produces [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") objects, not [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. Therefore, `fp.write()` must support [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") input.
If *ensure\_ascii* is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If *ensure\_ascii* is false, these characters will be output as-is.
json.dump(guilds, f, indent=4)
How would I go about adding my bot to the slash commands, and adding buttons for a soundboard?
reading the docs... and discord.py examples
got it all
How to check Send Message permission of bot in my Discord Channel?
!d discord.TextChannel.permissions_for
permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role").
This function takes into consideration the following cases...
elaborate
helping a friend start a discord bot but I forgot what I did to fix this problem. Created an venv and installed the imports on both venv and the main pc but the imports still wont read. restart did not work
pip install aiohttp?
!pip aiohttp ๐
What are you even trying to do
This is a clear instruction
Helping my friend start venv for discord bot
I know how to do that part but maybe he did it wrong
Open your project root and do what I said
!venv and activate in your IDE like exenifix said
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)
Then, to activate the new virtual environment:
Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate
Packages can then be installed to the virtual environment using pip, as normal.
For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.
Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.
Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
I am on unesco international forum
Do it then
Same actually
I'll be back in a week and will probably be busy anyway
;-;
You can contribute to my antispam bot if you'd like to ๐ค
Yea
open sourced?
Yeah
https://github.com/Exenifix/AIAS you could work on any issue you think can fix/implement
I am shortcuts fan

I even made autosetup not to write all cogs https://github.com/Exenifix/AIAS/blob/master/utils/bot.py#L134-L142
utils/bot.py lines 134 to 142
def auto_setup(self, module_name: str):
module = sys.modules[module_name]
members = inspect.getmembers(
module, lambda x: inspect.isclass(x) and issubclass(x, commands.Cog)
)
for member in members:
self.add_cog(member[1](self))
self.log.ok("%s loaded", module_name)```
Damn there's literal minister of culture of El Salvador speaking and I am here chatting ๐
She spoke spanish anyway I didn't understand a thing
๐ my library does that internally
fuk Disnake
K
i notice typos, ded
In your lib or in my bot?
Ah yes overring
Rich ppl dis days ๐ฟ
it doesn't load the cogs, but setup calls in modules
kinda same approach tho
Cooo
Cool* teach me this hax ๐ฟ
i use hooks that can be loaded/imported from modules and called directly instead of using load_extension
wyvern/utils.py lines 47 to 57
@attrs.define
class Hook:
"""Hooks for per-module setup. They can be loaded using `โGatewayClient.load_hooks`โ"""
callback: typing.Callable[..., typing.Any]
"""Callback of the hook."""
name: str
"""Name of the hook."""
def __call__(self, *args: typing.Any, **kwargs: typing.Any) -> typing.Any:
return self.callback(*args, **kwargs)```
pros of using this is you can have more than one for each file
# module.py
from wyvern import Plugin
from wyvern.utils import hook
plugin = Plugin()
@hook(name="load")
def load():
bot.add_plugin(Plugin())
@hook(name="unload")
def unload():
bot.unload_plugin(Plugin()/Plugin/just the name of plugin)
``` ```py
# bot.py
import wyvern
bot = wyvern.GatewayClient("token")
bot.load_hooks("module")
bot.hooks["load"]()
bot.run()
is how i plan to implement it
my bot is getting rate limited by discord
any solution ?
i just made self roles and after selection 3 or 4 roles at once i get this message by the hosting website
replit?
can be, cannot be
also i wanna ask
is there any limitations on discord about bot checking if someone has a role
like if it checks for like 20 roles if user has them
will discord rate limit it?
if its a cache operation, you shouldn't be facing any issue
hmmmmmmm
alright
probably daki.cc use shared servers
i changed the host
hope it works now
no you gotta wait a few minutes/hours or days lolz
its working on other host ๐ซ

Hi, I have a bot with a functie. With an infinite loop in a try catch statement so every error gets caught en function gets called again, that works fine but sometimes the function just stops running(see picture) without giving an error, I have a global restockkk variable thatโs set to true once the function starts running and set to false if an error is caught (in case the call in the catch fails) and on_ready checks if the restockkk value is false, if so it calls the function. But it stops without an error. How can I make something that checks if the infinite loop / function is still running?
.
As you can see it stopped at 9:08 without an error (I catch the errors and send them to the discord channel)
O.o
!d discord.Client.on_error ๐
await on_error(event_method, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default error handler provided by the client.
By default this logs to the library logger however it could be overridden to have a different implementation. Check [`on_error()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_error "discord.on_error") for more details.
Changed in version 2.0: `event_method` parameter is now positional-only and instead of writing to `sys.stderr` it logs instead.
Didn't understand most of this cause of too complex statement, could you please send on_ready code?
Yeah I will in about an hour when Iโm home
Sending errors to the thing that is the cause of errors doesn't sound like a great idea
The function, which performs requests and scrapes, is the cause of the error probably
Btw about infinite loops
Not the bot itself
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
Yep, but sending errors related to discord to discord just doesn't sound great
^^
What are the cons?
And Iโm not sure if i would be able to use with the way I use it
Every 2 minutes it scrapes a list of sites append something in a list and then compares them.
Not really any?
Sounds perfect for what you need
You can set it to run every 2 mins, then use mytask.start() and stop
Could you maybe help me if I canโt figure it out?
Iโll try it in half an hour when Iโm home
Oh my bad I meant pros
Ok great
I have to go soon so I wont be able to sorry
uhh they're just a lot cleaner and easy to use
If your loop is in on_ready event it might get called several times and you will have several loops running at the same time for no reason
hello everyone
@commands.command()
async def play(self, ctx: commands.Context, id: str):
id = id.strip()
if self.queue.get(ctx.guild.id) is None:
self.queue[ctx.guild.id] = []
song = self.api_zing.get_song_info(id)
self.queue.get(ctx.guild.id).append(song)
# check connect voice
voice = await self.join(ctx)
# check is playing
if ctx.voice_client.is_playing():
await ctx.send("ฤรฃ thรชm vร o hร ng chแป")
return
# play
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'option': '-vn'}
voice.play(
discord.FFmpegPCMAudio(
executable="./asset/ffmpeg/ffmpeg.exe",
source=self.api_zing.get_song_url(
self.queue[ctx.guild.id][0]["id"]),
after=lambda e: asyncio.create_task(self.next_song(ctx))),**FFMPEG_OPTIONS)
# volum
voice.source = discord.PCMVolumeTransformer(voice.source)
voice.source.volume = 1
return
async def next_song(self, ctx: commands.Context):
if len(self.queue.get(ctx.guild.id)) > 0:
voice = ctx.voice_client
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'option': '-vn'}
voice.play(
discord.FFmpegPCMAudio(
executable="./asset/ffmpeg/ffmpeg.exe",
source=self.api_zing.get_song_url(
self.queue[ctx.guild.id][0]["id"]),
after=lambda e: asyncio.create_task(self.next_song(ctx))),**FFMPEG_OPTIONS)
voice.source = discord.PCMVolumeTransformer(voice.source)
self.queue.get(ctx.guild.id).pop(0)
else:
await self.leave(ctx)
Exception ignored in: <function AudioSource.__del__ at 0x000001F718132E80>
Traceback (most recent call last):
File "C:\Users\Admin\Desktop\Discord Music\.venv\Lib\site-packages\discord\player.py", line 117, in __del__
self.cleanup()
File "C:\Users\Admin\Desktop\Discord Music\.venv\Lib\site-packages\discord\player.py", line 225, in cleanup
self._kill_process()
File "C:\Users\Admin\Desktop\Discord Music\.venv\Lib\site-packages\discord\player.py", line 190, in _kill_process
proc = self._process
^^^^^^^^^^^^^
AttributeError: 'FFmpegPCMAudio' object has no attribute '_process'
i can not play music
weather to retry starting the task if it once causes a failure
So it's true by default?
Cool, didn't know about that ๐
yes
Thx :]
Do u know how to use setup_hook? It's like calls one time after every restart but on_ready calls several time, ig setting setup_hook is same as on_ready event?
on_ready gets called everytime the bot recieves READY event from the gateway
setup_hook is a discord.py coro thats called before bot.start
Sometime it gets called on Resume ;-;
on_ready?
Yep
Ig so, not sure enough
well its meant to get called on every READY event
Btw is there anything like i can do if any gateway triggered like resume or warning then i can handle it?
hi , would this work ?
Hmmmmmm
!d discord.Member.avatar.save
No documentation found for the requested symbol.
๐คท
!d discord.Asset.save
await save(fp, *, seek_begin=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Saves this asset into a file-like object.
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
Cul
So
img=....avatar
imgs=await img.save()
?
anyone know about a youtube channel or something to learn discord.py? ๐คก
or docs is the better way?

so how may i do it ?
Docs as always better
But i recommend "Civo", "Glowstik" and "Swastik"
hi anyone
Civo is lik bit backdated, but he uses dpy v2
pls, can i help me
With what?
this
i started with docs but it kinda feels like i dont know what i am doing
If u finding a yt channel
It can happen for the first time so ye xd
That's like anyone who's new in coding
You'll get used to it eventually

yep i am trying
took me 3 whole days just to make a drop dow menu command ๐คก
Also u will not find all the stuff in a SINGLE video or a example site
Why clown emoji
Beside the docs
Idk, i am not familiar with ffmpeg
yeah ofc
but there are courses
i thought i can try finding one
thank
I c
V2 is full of with new stuffs
U will not find any video covering this stuff xd
well docs ftw ig ๐ฟ
How it can be defined if udoesn't import it ? ๐คท
can u tell which thing i need to import
from discord.ext import commands
That's a thing?
.ext
Never seen that one before ngl
Oh shut forgot
code
!eval [python_version] <code, ...>
Can also use: e
Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside of them.
By default your code is run on Python's 3.11 beta release, to assist with testing. If you run into issues related to this Python version, you can request the bot to use Python 3.10 by specifying the python_version arg and setting it to 3.10.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!
hello, how to implement like this
can change / to any i want? like !demo
No
ok, thanks!
I already fixed that error
@bot.event
async def on_ready():
logchannel = bot.get_channel(960147355691253800)
await logchannel.send(f'Logged in as {bot.user}'.format(bot))
await
global restockkk
if restockkk == False:
await restock()
beautiful
how can I have the on_submit for a modal return the answer of a field to be used elsewhere
all these people just sending the responses in an embed, I just want to store the answer and use it elsewhere
this doesnt work
instead of returning make the result an instance var of the class
then acess it through that coz i dont think its possible to return in on_submit
Nah using @tasks.loop is still better
okey, im trying now
Wth for are there 3 k's in restockkk
Also show restock() code
Because my function is called restock so i called the variable set to if the function is called restockkk to not mix it up
Not a good idea
okey, private or here? Its kinda big
Better would have used it in another tense
