#discord-bots
1 messages · Page 213 of 1
i think taking a message link would be even more annoying to use
a pastebin url
what was the field to get the value of the interaction response btw
well in all approaches you have to type the content anyway, and i guess one extra advantage would be having the ability to turn anyone's message into a tag without copy-pasting it
uhh value of what?
the response type that was used?
from send_message specifically
!d discord.Interaction.original_response
await original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the original interaction response message associated with the interaction.
If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).
Repeated calls to this will return a cached value.
thanks
is it just me or discord doesnt allow using slash commands while replying to a message?
no because it works just fine with /shrug ¯_(ツ)_/¯
unless they're somehow different
im talking about app commands from bots, not the default ones
it inherits from Message and doesnt override eq so likely yes
ok cool
huh, weird
i think it has worked for me in the past though with bot slash commands
normal
what's a better name, /tag remove or /tag delete
when replying
💀 i hope you get it but,
remove if you used add for adding tag
delete if you used create
and i am the exact opposite
sup
and i just dont code
sarth now busy with laif
preps
got some commitments cough
yes, JEE in 25 days
are dusre wali ki bat kar raha tha
shut
import os
from discord.ext import commands
from time import sleep
from discord import Intents
server = 1023935685654216714
token = os.environ['token']
client = commands.Bot(command_prefix="+", intents=Intents.all())
member = [911569948915171339]
@client.event
async def on_ready():
print("k")
sv = client.get_guild(server)
print(sv.members)
# for mem in sv.members:
# member.append(mem.id)
@client.command()
async def send(ctx):
for id in member:
user = client.get_user(id)
await user.send("Abc")
client.run(token, reconnect=True)
I got this code to run however is there a way to check if user has a certain role with the role's id?

users Don't have roles, members do
you need to use guild.get_member(USER_ID) and check if the member has the role using member.get_role(ROLE_ID)
I see, let me try
what are you gonna use the time module for?
role = 123456
@client.command()
async def send(ctx):
for id_ in member:
user = ctx.guild.get_member(id_) or await ctx.guild.fetch_member(id_)
if role in (i.id for i in user.roles):
try:
await user.send("Abc")
except discord.HTTPException:
continue
💀 Asher don't act like CHATGPT there's no Client.get_member
are something is there tho dont remember
Guild.get_member
probably yeah
not probably
aight
@c.command()
async def uwu(ctx):
to_send = [ ctx.guild.get_member(member)
for member in members
if ctx.guild.get_member(member).get_role(ROLE_ID)]
for m in to_send:
# do stuff
there should be try_object functions
what would that do?
try to get an object from the cache and fetch it if it isn't there
!d disnake.Client.get_or_fetch_user 🐢
await get_or_fetch_user(user_id, *, strict=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Tries to get the user from the cache. If fails, it tries to fetch the user from the API.
i mean its just a line
why would i switch to disnake when i could just code my own discord wrapper
someone could create a PR in the dpy repo but will probably not get accepted
u memorized docs or what
i remember anything I use often
if u had put this effort for jee u would be in iit by now 
client.get_user(...) or await client.fetch_user(...)?
i don't use my books often btw
yeah
bro saying that from kota
it's a basic function, honestly it could probably be the default behaviour or get_user even
yeah just subclass bot and add a method that does this lol
subclassing Guild to add try_member lol
is it even possible to subclass guild and have the library return that
oh yeah get_guild??? does that work
import discord
def foo(id):
# code
discord.Guild.foo = foo
that is the worst idea bruh
🗿then create your own fork
just modify dpy lib directly
then go try to flex in dpy server 
life accomplishment
3rd party code, get rekt
instant ban lol for discussing forks

Thank you, worked.
Thanks!
@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
data = await self.bot.db.fetchval('SELECT voice FROM voicemaster WHERE guild_id = $1', member.guild.id)
if data:
if after.channel.id and after.channel.id == data:
channel = await member.guild.create_voice_channel(name=f"{member.name}'s channel",
user_limit=0,
category=after.channel.category)
await member.move_to(channel)
await self.bot.db.execute('INSERT INTO voicemaster_data (voice, guild, owner) VALUES ($1, $2, $3)',
channel.id, channel.guild.id, member.id)
else:
vc = await self.bot.db.fetch('SELECT * FROM voicemaster_data WHERE voice = $1', before.channel.id)
if vc:
voice=before.channel.guild.get_channel(vc)
if voice:
if len(voice.members) == 0:
await voice.delete()
await self.bot.db.execute('DELETE FROM voicemaster_data WHERE voice = $1', before.channel.id)
It isn't getting the vc = await ... part, so the rest of the code doesn't work and i've got no clue to why. No errors in the console and I already added prints, thats how I found out it didnt reach the part.
I wanna know how to run multiple Discord clients simultaneously
Why
Trying to make it so if the channel that was created before becomes empty, it’ll delete that voicemaster channel
Hi! When a user types in the bot’s dm, this text appear. From there, they can choose if they want to create a ticket or cancel the interaction. Although, we found a glitch that if you send 2 messages, the text will sent twice and then, you will be able to create 2 tickets at once. Can someone help me to code so that the embed stops resending everytime they type in? My script is: https://paste.pythondiscord.com/yidukekala
u need to make a database where the ticket is stored so that user cannot create another
Can you help me with that?
Cause someone told me to do that
so
if user.id in list:
await ctx.send('you already got one open')
if user.id not in list:
list.append(user)
send the message or do stuff
# once completly done to close
list.remove(user)```
no lol i rarely spoonfeed ahem but we can help u if u have any query
nope
thats even worse than having 2 ticket messages
list is data type inbuilt and a keyword dont override it
also u didn't code that did u 
Nope
A friend did it for me
But they dont wanna help me no more unfortunately

Why?
in short u have to create which maps users to the tickets they created maybe message id or just a boolean value then update when ticket deleted
may u find the answer to that urself
No fr please

Does my code contain something suspicious?
i dont know i generally don't open pastebin on phone it freezes the screen
How did you know I didnt code that then
list.append
anyone who can make a view or dm ticket system this far wont make such a rookie mistake
is the view persistent?
They explained something to my that I was close to understand
But now your telling me that was completely wrong
like does it work even after u restart the bot?
The bot?
do the buttons in the ticket work after u restart the bot
No
lmao rip
Says interaction failed
That’s in dms btw
No tickets
That’s basically to create a ticket
then u might as well just do it with a list as a global variable
whoever made that ticket system didn't think it out
Smh
just make something like this
tickets = set()
# i am gonna assume they use on_message for dms
# if created
tickets.add(message.author.id)
# on top of that on_message add
if message.author.id in tickets:
return
# when ticket is deleted
tickets.remove(message.author.id)
Isn’t that exactly what they did?
if user.id in list:
await ctx.send('you already got one open')
if user.id not in list:
list.append(user)
send the message or do stuff
# once completly done to close
list.remove(user)```
ur not supposed to use list like that tho
u can do tickets = list() or [] like this but list is a keyword
plus he didn't return
What does return do btw
i mean thats probably the best i can do without a good database system
consider it as a way of telling the function to go no further and mind ur own business
Lmao
just make something like this
tickets = set()
# i am gonna assume they use on_message for dms
# if created
tickets.add(message.author.id)
# on top of that on_message add
if message.author.id in tickets:
return
# when ticket is deleted
tickets.remove(message.author.id)
So here the keyword is set?
hey
its a datatype yes
Okay ty ill try to do something with this 
sup
u can google what a set is its better suited for this use case hence i used it over list
micro optimisations 
#bot.py
import os
import discord
from discord import utils
from discord.ext import commands
from dotenv import load_dotenv
from dotenv import set_key
from dotenv import dotenv_values
import asyncio
load_dotenv()
get all variables from .env file
env_variables = dotenv_values('.env')
SERVER_ID = "..."
getting chat gpt vibe
async def token_log(token, category_name):
TOKEN = token
#CREATE A CATEGORY HERE AND PUT ID
intents = discord.Intents().all()
client = discord.Client(intents=intents, partials=["CHANNEL"])
channels = {}
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord')
@client.event
async def on_message(message):
server = client.get_guild(SERVER_ID)
category = utils.get(server.category_channels, name = category_name)
if isinstance(message.channel, discord.DMChannel) and message.author != client.user:
channel_name = f"{message.author.name}".lower().replace(" ", "-")
# check if there is existing channel with same name
existing_channel = utils.get(category.channels, name=channel_name)
if existing_channel:
print(client.get_channel(existing_channel.id))
await client.get_channel(existing_channel.id).send(f"!dm from {message.author}:{message.content}")
else:
overwrites = {
server.default_role: discord.PermissionOverwrite(read_messages=False),
server.me: discord.PermissionOverwrite(read_messages=True)
}
# Insert DM channel into channels dictionary
channels[channel_name] = message.channel
channel = await category.create_text_channel(channel_name, overwrites = overwrites)
await channel.send(f"!dm from {message.author}:{message.content}")
if not isinstance(message.channel, discord.DMChannel) and message.author == client.user:
if message.content.startswith("!dm"):
return
print(message.channel.name)
for x in channels.keys():
if message.channel.name == x:
await channels[x].send(f"{message.content}")
client.run(TOKEN, bot=False)
get token of bot
TOKEN = os.getenv('TOKEN')
intents = discord.Intents().all()
bot = commands.Bot(command_prefix="/", intents=intents)
@bot.event
async def on_ready():
print(f'{bot.user} has connected to Discord')
print(env_variables.items())
loop=asyncio.get_event_loop()
for key, value in env_variables.items():
if value ==TOKEN:
print("bot")
else:
loop.create_task(token_log(value, key))
loop.run_forever()
@bot.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(
f'Hi {member.name}, welcome to my Discord server!'
)
/addToken Name Token
@bot.command()
async def addToken(ctx, Token:str, Name:str):
try:
# add new variable to .env file
set_key('.env', Name, Token)
await ctx.message.guild.create_category(Name)
loop=asyncio.get_event_loop()
for key, value in env_variables.items():
if value ==TOKEN:
print("bot")
else:
loop.create_task(token_log(value, key))
loop.run_forever()
except Exception as errors:
print(f"Bot Error: {errors}")
bot.run(TOKEN)
This is my code, can anyone debug it?
chat gpt confirmed 
This is error below:
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Administrator\Music\1.py", line 86, in on_ready
loop.run_forever()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\asyncio\windows_events.py", line 319, in run_forever
assert self._self_reading_future is None
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError
its not as much as debug here its to rewrite the code
this will take a long time better to open a help channel in #1035199133436354600
discord.Intents.all() is a classmethod btw
().all() works too tho and thats like the least problematic issue 
hmm seems like he is trying to run multiple bots via a few commands and on_ready
@shrewd apex mm there's client.run(bot=False) 💀
there is both client and bot
aight
bruh just honestly learn coding get a decent job or clientele it's for ur own good 😔
bobux
how to edit a response from the bot (InteractionResponse)
await interaction.edit_original_response?
Saying it didn't work doesn't explain the problem
You didn't even explain your problem
use this
i tried
and what happened
nothing
??
event of what
of timeout
bruh
huh!!?
can any one help me out
like how to print, items of same keys in a dict
dict = {
"a" : "letter 1",
"a" : "letter 2"
}
dict.items()?
is this even possible
then it prints, only one value
!d discord.ui.View.remove_item
remove_item(item)```
Removes an item from the view.
This function returns the class instance to allow for fluent-style chaining.
!d nextcord.ui.Select
alias of StringSelect
Actually just match the channel topic
Hi, with discord.py it's possible to add a commande here ?
And it's possible have a field like this ?
ok thx
What do I do to replace the ‘ with , and mention all the roles?
!d str.replace
str.replace(old, new[, count])```
Return a copy of the string with all occurrences of substring *old* replaced by *new*. If the optional argument *count* is given, only the first *count* occurrences are replaced.
Might be useful
Removed the quotes and commas wb mentioning the roles?
You only have the name of the role?
Yea
!d str.join
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
If that is a list
I did this..
!d discord.utils.find
discord.utils.find(predicate, iterable, /)```
A helper to return the first element found in the sequence that meets the predicate. For example:
```py
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
``` would find the first [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") whose name is ‘Mighty’ and return it. If an entry is not found, then `None` is returned.
This is different from [`filter()`](https://docs.python.org/3/library/functions.html#filter "(in Python v3.11)") due to the fact it stops the moment it finds a valid entry.
Changed in version 2.0: Both parameters are now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.11)")s.
Look at this example of finding a Member with name
And try to convert it to finding a Role with name
role = discord.utils.find(lambda r: r.name == “role”, ctx.guild.roles)
Would work?
Eh wait what input data do you have and what output do you want to get
nvm
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Changed in version 2.0: The `iterable` parameter is now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.11)")s...
fortnite pfp?
👀
So in member_update (i don’t remember the event)or the event in which if a member’s roles are changed is it possible to only show the roles which are added/removed rather than every role the user is having
Just compare before.roles with after.roles and you can figure out which roles were added/removed
this gist is super outdated I swear 💀 (just haven't been on talking terms with discord.py so idk)
@client.event
async def on_member_update(before=discord.Member, after=discord.Member):
memb = discord.Member
channel = client.get_channel(1012255201547259975)
for role in memb.roles:
if before.roles != after.roles:
mbed = discord.Embed(title=f'{memb.display_name} | {before.roles} changed to {after.roles}')
await channel.send(embed=mbed)
output: TypeError: on_member 'property' is not iter object
idk how to use on_member_update💀
before=discord.Member, after=discord.Member why the =discord.Member?
async def on_member_update(before, after):
``` your function signature should just have two positional parameters
both of which are discord.Member objects
then what should i do with that
just like that?
yes, if you haven't used functions before I would highly recommend learning them
you have to typehint the arguments not set their default values to discord.Member
before: discord.Member, after: discord.Member
how do I access the everyone role for overwriting
ok thx
!d discord.Guild.default_role
property default_role```
Gets the @everyone role that all members have by default.
or you can usr the guild id itself
Finally, the mods do be testing if reactions should be enabled again in this channel
I've seen one in the last 12 hours
Prolly cz most of the ppl dk about it
everyone's just not used to being able to use them because nobody could be bothered to moderate them for the last 3 odd years lol
I mean, we still don't want to be bothered to moderate them
I think the problem there is that the server's attitude towards it has been moderating reactions, but it's not the reactions of people reacting inappropriately that should be moderated, it's the members, who probably shouldn't be here regardless of whether or not they can react since they're low quality users if they feel the need to behave in that way, but I digress, this isn't the channel and we have reactions for now /shrug
alec, the shrug slash command should be at the start of the message
But yea, u r right
I'm happy to give it a trial, it doesn't hurt to try things out and see what happens
look i have like 4 braincells and they cant all work at once 
Hahaha
Would it be possible to get some of the other discord bot libs in the channel description or a pin? I know pycord and nextcord are 2 major python bot libs that are still getting updated.
there is disnake, and discord.py is also there
If u want a different lib, there is hikari
+1 for nextcord/disnake in the description or a pin with lib alternatives 
your braincells aren't fearlessly concurrent? you should rewrite them in rust
I only have 2 threads, they can run with async concurrency but not actual parallelism

what's a good permission for deleting tags
manage server?? manage messages?
it will all be configurable anyways
I'd probably default it to manage server
better to default to a higher permission level if you're unsure, generally
that's what i thought
how do i get the number of chunks with as_chunks
as_chunks returns an iterator so figuring out the length from it wouldnt be possible unless you consumed it entirely, e.g. py chunks = [chunk for chunk in discord.utils.as_chunks(iterable)] len(chunks)
i just ended up doing list(chunks)
i thought it always returned an iterator of the same type
well it does return an iterator yielding elements of the same type as the iterable you pass to it, but iterators dont have a length
len(as_chunks(...)) would be incorrect because iterators dont know their length, which is why you would need to collect all the items into a sequence or enumerate over it instead
I think this is as safe as using a list comprehension
yeah
but wouldn't as_chunks return a list if it was given a list
oh nope its always an iterator
the function itself only cares that you're giving it an iterable/asynciterable as an argument
https://github.com/Rapptz/discord.py/blob/master/discord/utils.py#L1037-L1044
discord/utils.py lines 1037 to 1044
@overload
def as_chunks(iterator: AsyncIterable[T], max_size: int) -> AsyncIterator[List[T]]:
...
@overload
def as_chunks(iterator: Iterable[T], max_size: int) -> Iterator[List[T]]:
...```
since when can I do that
Oh I've been able to do that for an hour and 55 minutes
no, longer
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 370, in _scheduled_task
await item.callback(interaction)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup_v2\setup_view.py", line 319, in callback
eb = self.children[0]
AttributeError: 'SetupLanguageSelect' object has no attribute 'children'
show code
Bruh
property options```
A list of options that can be selected in this menu.
it would be self.options
and your nextcord seems to be outdated ( it's StringSelect now, not Select )
it's about the self.children i think
yes
when you're in the select class, self represents the Select which doesnt have a children attribute
view has that attr
does anyone wanna help me setup a file for running a discord bot, and getting a single command setup and from there i can figure out the rest
override the on_timeout method of the view
a file as in a basic bot script?
yes and then a single command that would get the discord users username
Overwrite?
https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py the repo has a decent example
class View(ui.View):
async def on_timeout(self):
# disable here
I dont want to disable it
I want to edit it after a select
you don't have to disable it
just add your own custom logic
also i have a question in #databases and i don't know if it's a database or discord timestamp issue
it's also a discord bot so
I have a view like this, but got likely the same error
how would i get the username of a user?
The user’s username.
with a bot to save their progress with the bot
ok so how would i get the id?
docs are cool
ok so for example i would do
pl.id = user.id
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 489, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 299, in on_application_command_error
raise error
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 888, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\cooldowns\cooldown.py", line 93, in inner
result = await func(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\server_moderation\cog.py", line 122, in edit_channel
await inter.response.send_message(view=ChannelSlowmode())
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 850, in send_message
payload["components"] = view.to_components()
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 201, in to_components
children = sorted(self.children, key=key)
AttributeError: 'ChannelSlowmode' object has no attribute 'children'``` it is now this error
for the player class so i can save their data for when they come back to play the game i can load their data using the bot
class ChannelSlowmode(nextcord.ui.View):
def __init__(self):
@nextcord.ui.string_select(placeholder="Please select a slowmode delay", max_values=1, options=["30 secound", "1 minute", "5 minutes", "10 minutes", "15 minutes", "30 minutes", "1 hour", "2 hours", "4 hours", "6 hours", "8 hours", "16 hours", "24 hours"])
async def on_select(self, select: nextcord.ui.StringSelect, inter: nextcord.Interaction):
option = select.values
match option:
case "30 secounds":
t = 30
case "1 minute":
t = 60
case "5 minutes":
t = 300
case "10 minutes":
t = 600
case "15 minutes":
t = 900
case "30 minutes":
t = 1800
case "1 hour":
t = 3600
case "2 hours":
t = 7200
case "4 hours":
t = 14400
case "6 hours":
t = 21600
case "8 hours":
t = 28800
case "16 hours":
t = 57600
case "24 hours":
t = 86400
await inter.channel.edit(slowmode_delay=t)
await self.message.edit(content="HI")```
but what if i wanted to send a message saying hello <insert username> when they start the game?
24 hour slowmode?
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
f"Hello, {user}"
what do you mean
you leaked your token in the screenshot
oh yeah thanks
but can you help
it keeps saying invalid token
but its a correct token
how'd you copy the token
using the copy button on the developer portal
can someone help with this i have a SQL table which has created_at set to DEFAULT NOW() AT TIME ZONE 'utc'
leaf/extensions/tags.py line 272
value=discord.utils.format_dt(tag_record["created_at"], "D"),```
and this is my code
i think the aware postgres timestamp is being converted to a naive timestamp somehow and discord.py is converting the naive timestamp to local time?
issue fixed - database was returning a utc-naive object so i wrapped pytz.UTC.localize around the datetime and it worked
hello everyone i want to create my voice channel in a categorie, how can i choose the id of my categorie for create a voice channel please ?
channel = await ctx.guild.create_voice_channel(f'{msg.content}')
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to create the channel.
The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
you can pass category argument
oh thanks ! i go test
i have an error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'id'
code?
channel = await ctx.guild.create_voice_channel(name=f'{msg.content}', category=1023283647006134364)
you need to pass CategoryChannel object not id of category
use bot.get_channel(1023283647006134364)
!d discord.utils.find
discord.utils.find(predicate, iterable, /)```
A helper to return the first element found in the sequence that meets the predicate. For example:
```py
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
``` would find the first [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") whose name is ‘Mighty’ and return it. If an entry is not found, then `None` is returned.
This is different from [`filter()`](https://docs.python.org/3/library/functions.html#filter "(in Python v3.11)") due to the fact it stops the moment it finds a valid entry.
Changed in version 2.0: Both parameters are now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.11)")s.
why
use this to find a category
category is treated as channel?
yup
then use get_channel
CategoryChannel ? the name of the channel ?
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
do this ```py
category = bot.get_channel(id)
nope special object representing a Category
which you can get using code i sent above
channel = await ctx.guild.create_voice_channel(name=f'{msg.content}', category=ctx.get_channel(1023283647006134364))
like that ?
oh ok
👍
how can I get the missing permission out of missing permissions
do you want to get all the missing permissions or a specific missing permissions?
it's get_channel
If missing permissions occurs during a command, it should display the missing permission(s).
it's just error.missing_permissions
Tried
wdym?
How to handle this in a error handler? @smoky sinew
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 490, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 299, in on_application_command_error
raise error
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 890, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\cooldowns\cooldown.py", line 93, in inner
result = await func(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\user_information\cog.py", line 168, in userinfo
async with interaction.channel.typing():
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\context_managers.py", line 60, in __aenter__
await channel._state.http.send_typing(channel.id)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\http.py", line 394, in request
raise Forbidden(response, data)
nextcord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
that's not MissingPermissions though
that's just forbidden
you can handle that with try/except
since i see interaction.channel.typing i'm just going to take a wild guess and say that the application command was invoked in a channel the bot does not have access to
isinstance(error, MissingPermissions)
also i would not recommend you to make an error handler like this because you are basically removing all helpful errors from your terminal
that doesn't help..
to what library are you referring to?
The bot has acces
discord.py? all forks have that though
I mean you just said it doesn't work without giving any details so I have to guess I guess
ah I was searching it at api.html, I found out that it is located at ext/commands.html 😔
Why do my buttons stop working after around 15 minutes? Is there Any way of fixing that?
no timeout and persistent views?
how to run discord bot with database for free
self-host it
There are some pterodactyl based hosting servers on discord, some are free, but i wouldn't trust them
hmm
How do i make it so it never stops working?
add custom_id to all items, set timeout to None, and add the view in setup_hook or somewhere else
no
What is with_message at await interaction.response.defer()
can you explain more?
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
ah?
no idea also
hello, where can I find docs for using slash commands with discord.py (import discord)
I already tried to search slash commands in there, but I couldn't
!d discord.app_commands.Command
class discord.app_commands.Command(*, name, description, callback, nsfw=False, parent=None, guild_ids=None, auto_locale_strings=True, extras=...)```
A class that implements an application command.
These are usually not created manually, instead they are created using one of the following decorators:
• [`command()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.command "discord.app_commands.command")
• [`Group.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group.command "discord.app_commands.Group.command")
• [`CommandTree.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.command "discord.app_commands.CommandTree.command")...
Thanks!
Also
How can I do so the bot doesn't have to handle command by command? (so that it can handle each command on its own thread or stuff like that, hope you get the point)
It should already be doing that to some degree
idk, it felt kinda slow
what are you doing inside the command?
simple ping command
if command[0] == 'ping':
print(self.latency)
await message.channel.send(f":ping_pong: Pong! {round(self.latency * 10)}ms")
how can I change the bot's status?
!d discord.Client.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter...
How would I make a bot that checks other bots' status and if the bot detects a bot that went offline how would I like to send a message that BotX went offline?
loop through all members every x
create task that runs every x minutes/seconds and loop over guild members check if member is a bot then check status and then send message to some channel
you forgot smt
what did i forget?
it will send the message every x seconds for all offlibe bots
so if a bot goes offfline
it will send the message until it gets online
right we need to create some cache thingy
basically
you could just use a json file with a list
or even a txt file with the ids separated by a space
so you also need to create easiest way i would go for bot varriable like bot.bots_offline and store it here
then check if it was already offline since last checkout
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
I changed my discord bots intents so he could read messages. But it won't work, do I need to refresh the bot in some way?
I remember there's like a specific line of code I need to call no?
did you enable it on developer portal?
Yeah
then you need to add it in code
I have bot = discord.Client(intents=discord.Intents.default()) which I believe is correct for messaging intent
intents = ...
intents.message_content = True```
yes its not on
so you need to define intents before client
then enable intent you want
then pass the intents varriable to Client
When using this code:
class PersistentViewBot(commands.Bot):
def __init__(self):
intents = discord.Intents().all()
super().__init__(command_prefix=commands.when_mentioned_or('.'), intents=intents)
async def setup_hook(self) -> None:
#interaction = discord.Interaction()
self.add_view(signupButton())
Im getting the error that signupButton.init() missing 1 positional argument: 'interaction'
But it's not suposed to take it because I'm not calling the function I just want to make the button persistent
Can we see class signupButton?
how does the signupButton looks like
class signupButton(discord.ui.Button):
def __init__(self, interaction):
super().__init__(style=discord.ButtonStyle.green, label="Sign up", custom_id="1")
async def callback(self, interaction: discord.Interaction):
await add_user(interaction)
so you accept interaction inside __init__ method
which you dont want here
just remove interaction argument from init
could somebody quickly explain about these? what each client / intents
intents = discord.Intents.default()
intents.message_content = True
client = MyClient(intents=intents)
client.run(TOKEN)
I cant create slash commands because I don't know what to type after the @
The Error:
@app_commands.command(description="Clear messages from a channel")
NameError: name 'app_commands' is not defined
you are missing this import from discord import app_commands
why not just save a list of bot members
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py here is a small example of how basic slash command looks like
hm?
cache them and loop over the cached bot members
instead of always looping through the full member list'
Now im getting the error: TypeError(f'expected an instance of View not {view.class.name}')
for the line
self.add_view(signupButton())
could be but what if you add a bot to a server while its going
i'm assuming he's just making an uptime command for a certain amount of fbots
what is signupButton
class signupButton(discord.ui.Button):
def __init__(self):
super().__init__(style=discord.ButtonStyle.green, label="Sign up", custom_id="1")
async def callback(self, interaction: discord.Interaction):
await add_user(interaction)
it must be a View
not Button
View can hold a Button as item
so I should change discord.ui.Button to discord.ui.View?
https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py this is an example of a persistent view that holds 3 buttons check it out
not really
class SignUpView(discord.ui.View):
@discord.ui.button(label="Sign Up", custom_id="sign_up", style=discord.ButtonStyle.green)
async def sign_up(self, interaction, button):
await add_user(interaction)
try something like this and use button as a decorator
someone review pls
How could I change this code to just list the users usernames instead of pinging them? py user_mentions = ' '.join([f'<@{user[0]}>' for user in users])
' '.join(user.name for user in users)
also for pinging you can do user.mention
Sick, thanks!
I think I'm gonna be making a command soon that does have to ping the user, so thanks!
Why not upgrading to latest?
what's the full error
probably self-bot as discord.py 1.7.3 is the last version that supports them lol
Is there a shutdown function? I know it used to be like this: await ctx.bot.logout()But I'm not sure if it changed with the more recent versions
(I'm tryna make a /shutdown command, if that means anything)
nah
im good
there is no legitimate reason to still be using discord.py 1.7.3
that doesn't exist anymore
you should just use await bot.close()
Alr, thx
full error:
message.author.avatar
Thank you
because display_avatar was added in 2.0
property display_avatar```
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
oh nvm it was only display_name then
that’s where i got confused
i thought it was already a thing
How can I use the verification_task variable to let other functions in your code know when the task is running?
verification_task = False
@tasks.loop(hours=24)
async def update_elo_ratings():
verification_task = True
# rest of the function ...
verification_task = False
Well, exactly what code u have.
What do you mean?
Well verification_task will be True when its running and false when its not.
I want to use it as a global variable to let other functions know when it's true or false
i did a thing... ```py
@commands.command(name='clear')
@commands.has_permissions(manage_messages=True)
async def clear(self, ctx, limit=None, channel: discord.TextChannel=None):
if (_id := ctx.message.reference.message_id) is not None: # check if the command was a reply
history = ctx.channel.history(limit=None) # if its a reply, we by nature want to clear the channel we sent it in, so just get the message history
reply = await ctx.channel.fetch_message(_id) # store the reply
limit = 0
async for msg in history:
limit += 1 # increase limit for each message we loop through
if msg == reply: # if the message is the one we replied to, stop looping
break
if channel is not None: # if a channel is specified, clear that channel
toclear = channel
else:
toclear = ctx.channel # otherwise clear the current channel
if limit is None: limit = 50 # default limit to 50
await toclear.purge(limit=int(limit)) # purge the target channel
global verification_task```
R u saying that per task, u want a way to see if its done or not?
Oh so like
verification_task = False
@tasks.loop(hours=24)
async def update_elo_ratings():
global verification_task
verification_task = True
# rest of the function ...
verification_task = False
Right?
global verification_task
@tasks.loop(hours=24)
async def update_elo_ratings():
verification_task = True
# rest of the function ...
verification_task = False```
Will it be true or false after I start the Discord bot, if we ignore @tasks.loop(hours=24)
not sure. print it out
!e
global verification_task
print(verification_task)```
@young dagger :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 3, in <module>
003 | print(verification_task)
004 | ^^^^^^^^^^^^^^^^^
005 | NameError: name 'verification_task' is not defined
@gusty flax :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | global verification_task = False
003 | ^
004 | SyntaxError: invalid syntax
globals are annoying to use lowkey
I just use classes and have attributes.
Tho Im not sure what ur trying to do.
verification_task = False
@tasks.loop(hours=24)
async def update_elo_ratings():
verification_task = True
# rest of the function ...
verification_task = False
@client.event
async def on_member_join(member):
if not verification_task:
# rest of the function ...
Oh ye. that works. bc its a reference.
That code willw ork.
No its greyed out
wdym
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.
I don't think there is need for that
Well, I wanna see ur indentation. But put ur mouse over that line and tell me the message.
Thats true, it is in local scope. U would have to use global
So,
@tasks.loop(hours=24)
async def update_elo_ratings():
global verification_task
verification_task = True```
Or am I wrong?
verification_task = False
@tasks.loop(hours=24)
async def update_elo_ratings():
global verification_task
verification_task = True```
This shld work
Do I specify it in the other function as well?
@client.event
async def on_member_join(member):
global verification_task
if not verification_task:
# rest of the function ...```
sry i dont use globals that much. i forgot how they work 😓
Even if I only need to access verification_task to see if it's True or False?
I still need to declare it as global?
Yes, cause each function has its own scope. U need to access that outer scope, and u would access it as a global.
Thast why most ppl use classes, with attributes. Generally, globals aren't suggested.
It seems like it can read it without declaring it as global
Can somebody else please confirm?
Show code.
Sorry, I don't mean to be rude, but there is no need to show you the code as I already explained what I want to do
💀 I want to see which value ur talking about. It is much easier to help seeing the code.
I know what u want to do, but idk what ur doing
I think this already explains it
😅 well I just checked and u dont need global
!e```py
boolean = False
def myfunc():
global boolean
boolean = True
def checker():
global boolean
print(boolean)
print(boolean)
myfunc()
print(boolean)
checker()```
@gusty flax :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | False
002 | True
003 | True
!e```py
boolean = False
def myfunc():
global boolean
boolean = True
def checker():
print(boolean)
print(boolean)
myfunc()
print(boolean)
checker()```
@gusty flax :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | False
002 | True
003 | True
its the same
seems that u can access it but not reassign it unless u access the global
Thank you
hi, I am dealing with requests and the bot returns 403 when you can access it no problem via google why may that be? py await interaction.response.send_message(f"The website responded with the status code: {requests.get(url=url).status_code} \n {requests.get(url=url).reason}")
@young dagger you need to declare variable as global if it is redefined in function scope
- You are most likely missing authorization header. Read about authorization on docs of API you are using
- You should make single request
r = requests.get(...)
print(r.status_code, r.reason)
By calling requests.get() twice you make 2 requests, however you need only one
3. In async applications, you need to avoid blocking. Instead of requests, use aiohttp (which dpy already uses), google its docs and read client quickstart
Answer is simple - don't use replit for hosting 😇
On other sites it is returning 200 but I found the site I was testing is using cloudflare
I pretty much explained everything
i mean im using for testing, so any other good site?
Local host using vscode
There aren't really "sites" for hosting bots, instead there are cloud servers (VPS)
Good idea
it takes horrible starting time on my local host idk why, but works fine on replit
Ok where do I find quickstart for it?
like i have to sit for around 5 mins with a blank console
Internet speeds maybe
I pretty much told you how 😃
could be
Ok
Like ofc I can go to google, find its docs and send the link to you but I think it's not that hard
Right ok
If you have any struggles tell me tho
Will do
the quickstart i half understood
can you provide a discord example?
don't use requests with discord.py
use aiohttp instead
🤦🏽♂️
async with aiohttp.ClientSession() as session:
r = await session.get(...)
data = await r.json()```
session.get has args and kwargs very similar to requests.get if not the same
So you shouldn't have trouble with figuring it out
ok how do i include a link same as before?
"has args and kwargs very similar"
ah.
Hey, everytime i try to get the guild it spits out the guild's object inside of my cog (i am trying to make welcoming.)
@commands.Cog.listener()
async def on_member_join(self, member):
guild = discord.Guild
try:
with open("welcome.json", "r") as e:
fr = json.load(e)
message = fr[guild.id]["message"]
channel = fr[guild.id][int("channel")]
if "{user.mention}" in message:
message.replace("{user.mention}", member.mention)
await channel.send(str(message))
except Exception as e:
print(e)```
Error:
```py
<member 'id' of 'Guild' objects>```
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
it keeps giving my the guild's object when im trying to get the guild's id for the welcome dataset
how would I show the reason it reuturned the code?
please paste the error in the console to us
<member 'id' of 'Guild' objects>```
its returning this since i put it in a try method
and i made it print out the error
the full thing not just that
it is only that
I highly doubt this is printed by code you provided
@commands.Cog.listener()
async def on_member_join(self, member):
guild = discord.Guild
try:
with open("welcome.json", "r") as e:
fr = json.load(e)
message = fr[guild.id]["message"]
channel = fr[guild.id][int("channel")]
if "{user.mention}" in message:
message.replace("{user.mention}", member.mention)
await channel.send(str(message))
except Exception as e:
print(e)```
Exceptions just don't look like that
Obviously it does if its giving me an object erorr
Don't handle exceptions at that point
dont know why tbh
Try adding additional information like "exception occurred at on_member_join"
And see if it is really printed there
remove the try and except and try again
i got part of it to work but how do i display the reason it gave the code?
There must be methods of response in api reference, try searching it
class aiohttp.ClientResponse```
Client response returned by [`aiohttp.ClientSession.request()`](https://aiohttp.readthedocs.io/en/stable/client_reference.html#aiohttp.ClientSession.request "aiohttp.ClientSession.request") and family.
User never creates the instance of ClientResponse class but gets it from API calls.
[`ClientResponse`](https://aiohttp.readthedocs.io/en/stable/client_reference.html#aiohttp.ClientResponse "aiohttp.ClientResponse") supports async context manager protocol, e.g.:
```py
resp = await client_session.get(url)
async with resp:
assert resp.status == 200
``` After exiting from `async with` block response object will be *released* (see [`release()`](https://aiohttp.readthedocs.io/en/stable/client_reference.html#aiohttp.ClientResponse.release "aiohttp.ClientResponse.release") coroutine).
@echo wasp this class's methods
ok
ah well every single time i try to define the guild into on_member_join it gives me an TypeError every single time
@slate swan it's member.guild in your case
hmm interesting, ill look into it
I got the status but i was using a reason before with {requests.get(url=url).reason}
how do i add a auth header
how do i add a auth header i can't find it in the docs
Now it prints out the guild.id when im trying to fetch the channel ID from the db to send the message.
what does your code look like now?
@commands.Cog.listener()
async def on_member_join(self, member):
guild = member.guild
try:
with open("welcome.json", "r") as e:
fr = json.load(e)
message = fr[guild.id]["message"]
channel = fr[guild.id]["channel"]
if "{user.mention}" in message:
message.replace("{user.mention}", member.mention)
await channel.send(str(message))
except Exception as x:
print(x)```
where is it printing the guild id?
i believe the Exception is outputting the guild id but idk how
can you remove the try and except from the statement and try the thing again and see if it gives you a trace back?
is that a real guild if so remove that id
if i remove it the DB would not know what message to send/the channel id
{
"": {
"message": "hello {user.mention}, please wait while an administrator view your join request.",
"channel": ""
}
}```
do i set the guild id in the db as an int aswell?
OH I THINK I KNOW WHAT I DID WRONG
no
please remove your guild id from the discord messages!
now!
i dont get it know im confused..
remove the guild id from the messages you are sending to us
it is a security issue
did your issue get fixed?
guild id right here
Nope i still have an issue, int issue
channel = fr[str(member.guild.id)][int("channel")]
ValueError: invalid literal for int() with base 10: 'channel'```
ah wait i think i know
did you know?
I believe since im getting the channel from the db, its sending it as "1234" so if i make another variable and place that channel variable in it i could maybe get it to spit out just 123?
@echo wasp correct
i have no idea give it a try
did it work?
did you get it working?
do you happen to know how to make an auth header to make it past this
Are you trying to use API or webscrap?
What API are you using
But if it's off its a 200 and aiohttp like you told me to use
Aiohttp
Actually it is but not in way I meant it
No I want to know a status of a website and that being on gives it a 403 and a Javascript it has to complete if that is off it gives the 200 like it should but alot of sites may have that on
I think so-called protection is basically authorization, not sure what they're trying to do tho
You're pinging a site so basically? 🗿
Bru
May add on to it todo more later on
Like if it Returns anything but a 200 send a message
Later on down the road
Well in that case everything besides 5xx errors would mean site is functioning
Ok. So just leave it alone and don't add a Auth header?
If site does not belong to you to obviously can't
Well how do they get past the java script challenge?
Because services like better uptime gets past it.
The bot is a status checker
Checks discord bots, websites, and minecraft servers. It can send a down message and publish it for anyone that may be hosting a minecraft server bots, or a website.
If a server is malfunctioning you will either receive 5xx code or not receive anything at all
Ok so just don't build the auth header ok
Thanks
Yo
anyone know how to make talk bot
i think u meant chatbot
just use some api like chat gpt and u are good to go
!pypi chatterbot if ur looking more long term
oh ty
you want at least a gpt level bot that one is pretty old
oh
Train own model with tensorflow 🤓
I'm making one with the llama model and there are a few on github
You will need uh text vectorization, embedding and some RNN layer
It takes much time to Respond
Has alot of flaws.
It doesn't work properly.
Train your own model or Chatgpt.
is client.logout() a thing?
Can I use the first code instead of the second?
elo_rating = await calculate_mmr(summoner_id, RIOT_API_KEY) or user['elo_rating']```
```python
elo_rating = await calculate_mmr(summoner_id, RIOT_API_KEY)
if elo_rating is None:
elo_rating = user['elo_rating']```
!d discord.Client.logout
No documentation found for the requested symbol.
question answered
logout is only available in earlier version afaik
now it's
!d discord.Client.close
await close()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Closes the connection to Discord.
await start(token, *, reconnect=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shorthand coroutine for [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login") + [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect "discord.Client.connect").
ah ty
Can I do do this?
# return the values as a tuple
return tier, rank, lp
# And then create a tuple consisting of only tier and rank
tier, rank, lp = await get_tier_and_rank(summoner_id, RIOT_API_KEY)
tier_and_rank = tier, rank```
Yes u can.
not really, everything after return wont be executed
!e ```py
def f():
print("Hello")
return
print("World")
f()
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello
If I return tier, rank, and lp, how can I define the code to set only the tier and rank as tier_and_rank?
lp should not be included
tier_and_rank = await get_tier_and_rank(summoner_id, RIOT_API_KEY)[:-1]
Will it add a space in between them, so that the result has the format "Silver 3" example?
no it neither do that in your solution
use this to do that
!d str.join
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
So something like this?
return f"{tier} {rank} {lp}"
tier_and_rank = await get_tier_and_rank(summoner_id, RIOT_API_KEY)
tier, rank, lp = tier_and_rank.split()
tier_and_rank = f"{tier} {rank}"```
try
Should work unless there is more space on "tier" stuff
Or simply return a list
return [tier, rank, lp]
So in that case I could just do:
return [tier, rank, lp]
tier_and_rank = await get_tier_and_rank(summoner_id, RIOT_API_KEY)
tier, rank, lp = tier_and_rank.split()
tier_and_rank = [tier, rank]```
Right?
wait actually just do
return [tier, rank, lp]
....
.....
tier, rank, lp=tier_and_rank
tier_and_rank=f"{tier} {rank}"
Idk what are you trying to do tho
I want some functions to use tier, rank, and LP, and others to only use tier and rank
For this example, I only want to update the user's tier and rank in the database without including LP
Then the code i have given should work tho
So there is a function to get those 3 informations
But rn you want to fetch 2 of them?
Correct
# Check tier, rank and LP
for entry in data:
if entry['queueType'] == 'RANKED_SOLO_5x5':
tier = entry['tier']
rank = entry['rank']
lp = entry["leaguePoints"]
return f"{tier} {rank} {lp}"
tier_and_rank = await get_tier_and_rank(summoner_id, RIOT_API_KEY)
# Should only add tier and rank without including LP, example "Silver III"
await collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier_and_rank": tier_and_rank}})```
Return the list
return [tier, rank, lp]
t_a_e=f"{tier_and_rank[0]} {tier_and_rank[1]}"
Hi,
im having issues with loading classes into one file
This is my main file code
import glob
import importlib
import time
import discord
from discord.ext import commands
BOT_TOKEN = "my Bot token"
bot = commands.Bot(command_prefix='?', intents=discord.Intents.all())
# Set the directory containing the modules
modules_dir = 'my directory'
# Find all Python module files in the directory
module_files = glob.glob(os.path.join(modules_dir, '*.py'))
# Load each module and register all commands and cogs found
for module_file in module_files:
# Import the module
module_name = os.path.splitext(os.path.basename(module_file))[0]
module = importlib.import_module(module_name)
# Look for commands and cogs in the module and register them to the bot
for obj in list(module.__dict__.values()):
if isinstance(obj, commands.Command):
bot.add_command(obj)
elif isinstance(obj, type) and issubclass(obj, commands.Cog):
bot.add_cog(obj(bot))
if "Test" in bot.cogs:
print("TestCog is loaded!")
else:
print("TestCog is not loaded!")
bot.run(BOT_TOKEN)
This is my test file code
from discord.ext import commands
class Test(commands.Cog, name='test'):
__module__ = 'test'
def __init__(self, bot):
self.bot = bot
@commands.command(name='test')
async def test(self, ctx):
await ctx.send("Bot is online")
def setup(bot):
print('Loading Test cog...')
bot.add_cog(Test(bot))```
the error im getting on cmd after starting the bot and typing ?test in a server its in
TestCog is not loaded!
TestCog is not loaded!
TestCog is not loaded!
TestCog is not loaded!
TestCog is not loaded!
TestCog is not loaded!
TestCog is not loaded!
TestCog is not loaded!
TestCog is not loaded!
TestCog is not loaded!
TestCog is not loaded!
TestCog is not loaded!
TestCog is not loaded!
TestCog is not loaded!
TestCog is not loaded!
TestCog is not loaded!
TestCog is not loaded!
TestCog is not loaded!
TestCog is not loaded!
TestCog is not loaded!
TestCog is not loaded!
C:\Users\saeed\Desktop\Saeed\Year 3\Project\E-learning\E-learning\Main.py:30: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(obj(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
[2023-03-13 21:18:16] [INFO ] discord.client: logging in using static token
[2023-03-13 21:18:17] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: d9548544f61dcb03c17e830b5656b0f4).
[2023-03-13 21:18:21] [ERROR ] discord.ext.commands.bot: Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "test" is not found
im trying to make bot.add_cog await but im struggling to do it. do u guys know how
to fix the error
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...
It's coroutine btw
yea i figured but when i try to make it await i get a lot of errors.
so technically
async def setup(bot):
await bot.add_cog(....)
ty i think thats what i done but let me try again
Ig
Actually you got a runtime warning too
isn't bc bot.add_cog is not await? or something diff
You need to
await add_cog in main.py too
ye i had errors awaiting it in the main.py too bc its meant to be outisde the loop then when i tried to do that i had diff errors. let me do it again and show u
Yeah i got it
Add all codes to a async function then just ah do asyncio.run()
Or do it on setup_hook or on_ready
ok let me try that thank you
i get this error @shrewd fjord
asyncio.run() cannot be called from a running event loop
this is my new code
import glob
import importlib
import time
import discord
from discord.ext import commands
import asyncio
BOT_TOKEN = "Bot token"
async def start_bot():
bot = commands.Bot(command_prefix='?', intents=discord.Intents.all())
# Set the directory containing the modules
modules_dir = 'C:/Users/saeed/Desktop/Saeed/Year 3/Project/E-learning/E-learning'
# Find all Python module files in the directory
module_files = glob.glob(os.path.join(modules_dir, '*.py'))
# Load each module and register all commands and cogs found
for module_file in module_files:
# Import the module
module_name = os.path.splitext(os.path.basename(module_file))[0]
module = importlib.import_module(module_name)
# Look for commands and cogs in the module and register them to the bot
for obj in list(module.__dict__.values()):
if isinstance(obj, commands.Command):
bot.add_command(obj)
elif isinstance(obj, type) and issubclass(obj, commands.Cog):
await bot.add_cog(obj(bot))
if "Test" in bot.cogs:
print("TestCog is loaded!")
else:
print("TestCog is not loaded!")
await bot.start(BOT_TOKEN)
asyncio.run(start_bot())```
I created a bot.wait_for('reaction_add')
how can i get the name of the user who clicked the reaction ?
reaction, user = await bot.wait_for("reaction_add", ...)
thanks
Why ?.
Hello please. I was trying to run the avatarify program then my network got unstable and I got busy and then later I wanted to continue or restart I keep getting the error user already exist.
Please my question is, is there a way I can clear the history on the Conda because I have uninstalled and reinstalled I still get the same thing saying data already exists. Please help would be very much appreciated 🙏.
if you are simply wanting to clone (which to me sounds like you don't need to save any changes you made) then just delete the directory
this isn't the right channel to ask this question, you should open an help post at #1035199133436354600
Okay I’ll do that thanks
I deleted the whole conda file and stuff, is there a means of reset or refresh or delete old stuff?
what intents do you have?
I am not familiar with conda, but git clone is just a basic file directory. As Snipy said though, this channel is more for discord bot development
yeah
done, nothing changed
otherwise your bot isn't able to receive on_reaction_add events and so it can't update its cache
guys can anyyone help me with this plss, i been spending ages trying to load all cogs from one file
do you have intents.messages enabled?
nope
How do i get the permissions string to display what permissions they are missing in my error hander?
For instance: "You're missing the ban_members permission"
I'm tryna display ban_members or manage_guild in my message
enable it and try
have you tried printing just the exception message? Assuming it is generic?
!d discord.ext.commands.MissingPermissions.missing_permissions
The required permissions that are missing.
oh
when a MissingPermissions error is raised you can access the missing_permissions attribute
alright but the error basically displays as ['ban_members'] how do i remove the [' '] from the message
lol
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
or if it's just the first item of the list, just use it's index
@vocal snow wanna join pyweek?
what is that 👻
we make games using python
I think he's sarcastic

are you still looking for people 
yep
me sarth n snipy
will there be a group chat or server?
care to join 
yeah 100%
yeah server
ok dm me the invite
Is it possible to get someone's nickname history?
maybe audit log ig but best wau would be to track it on ur own 
u dont need discord components
oh
discord.py has everything interaction slash commands buttons and stuff
ur code what do i know replace discord components with discord.py
discord components is a third party outdated library
Hi, how can I get whole traceback as string?
Use disnake library
Why are you using save from.net 
trying to make a bot look at the few messages before it and look for the latest mention of itself. Then it should store the mentions in that message. How would I do that?
!d traceback.format_exception
traceback.format_exception(exc, /, [value, tb, ]limit=None, chain=True)```
Format a stack trace and the exception information. The arguments have the same meaning as the corresponding arguments to [`print_exception()`](https://docs.python.org/3/library/traceback.html#traceback.print_exception "traceback.print_exception"). The return value is a list of strings, each ending in a newline and some containing internal newlines. When these lines are concatenated and printed, exactly the same text is printed as does [`print_exception()`](https://docs.python.org/3/library/traceback.html#traceback.print_exception "traceback.print_exception").
Changed in version 3.5: The *etype* argument is ignored and inferred from the type of *value*.
Changed in version 3.10: This function’s behavior and signature were modified to match [`print_exception()`](https://docs.python.org/3/library/traceback.html#traceback.print_exception "traceback.print_exception").
Thanks
how do i allow it to delete a certain channel after every hour? I've tried this but it needs an ID
@tasks.loop(minutes=60)
async def edit_channel():
general = bot.get_channel(1085241822248435844)
new_channel = await general.clone(reason="Channel was purged")
await new_channel.edit(position=general.position)
await general.delete()
await new_channel.send("This channel has been **purged**. Every **hour** this channel will be deleted. We do this to ensure the server's **safety**")```
@turbid canopy (sorry for pings its for dm i can't dm if i didn't ping and there is 50k online memberd
Bruh
Plz accept the dm
what's wrong with it
!d discord.ext.commands.Bot.fetch_channel
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel"), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.PrivateChannel "discord.abc.PrivateChannel"), or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread "discord.Thread") with the specified ID.
Note
This method is an API call. For general usage, consider [`get_channel()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_channel "discord.ext.commands.Bot.get_channel") instead.
New in version 1.2.
Changed in version 2.0: `channel_id` parameter is now positional-only.
maybe that
it wont delete the channel after the orginial channel has been deleted, because the ID is wrong. so i wont to do it without the id
How can i set my bot's discord status using the gateway/api
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
np
store it then
@tasks.loop(minutes=60)
async def edit_channel():
general = bot.get_channel(bot.last_channel.id)
new_channel = await general.clone(reason="Channel was purged")
await new_channel.edit(position=general.position)
await general.delete()
await new_channel.send("This channel has been **purged**. Every **hour** this channel will be deleted. We do this to ensure the server's **safety**")
bot.last_channel = new_channel
should that work?
:v
ill try
yup
wait couldn't i just loop through the category and check if a channel with a certain name is there?
Wait, what about status, not presence
for channel in category.channels:
if "「🥥」・chat" in category:```
why would you do that
i dont really understand the way youre saying i shuld do it
youre saying to store the ID but the channel gets deleted every hour
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
I am storing the new channel
so I delete the last new channel
and set the variable again to be the new channel
i tried your code but got an error
I need to see the error for know what's happening
AttributeError: 'MyBot' object has no attribute 'last_channel'```
uhh
get channel can't take None as an arg?
i dont have an init
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.
my whole code?
yeah
its 3k lines long
!discord.ext.commands.Bot.fetch_channel
an only file?
yes
!d discord.ext.commands.Bot.fetch_channel
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel"), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.PrivateChannel "discord.abc.PrivateChannel"), or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread "discord.Thread") with the specified ID.
Note
This method is an API call. For general usage, consider [`get_channel()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_channel "discord.ext.commands.Bot.get_channel") instead.
New in version 1.2.
Changed in version 2.0: `channel_id` parameter is now positional-only.
i dont like cogs
not if i know where evrything in my code is
it is.
anyway back to the problem
the problem rn is your unorganised code
its not
you should use cogs
set bot.last_channel to None on init
i dont have an init though
see how it is an issue
💀
surely theres another way without needing to use init
yeah, the wrong way
he can still configure it as None even without a commands.Bot subclass
he needs to get track of it
just add
MyBot.last_channel = None right after the definition of MyBot
doesn't feel right 💀
it should, because that's totally valid
technically the only thing that changes is the time when the attribute is defined
MyBot = commands.Bot(...)
MyBot.last_channel = None
# commands and other things below
similarly, you don't inherit discord.Intents just to override the default attributes
you do
intents = discord.Intents.default()
intents.message_content = True
etc...
AttributeError: 'NoneType' object has no attribute 'id'
instead of storing a discord.TextChannel store an int
yeah you need to check if MyBot.last_channel is None
yeah, instead if it's None you need to start the logic where you do things to create the category (or to do something else, actually I don't know your usecase)
i just want it to delete a channel every hour and remake it
ok but the first time (when the bot starts) you don't have the channel cached yet so you need to come up with a logic to fetch it or to do something else
why wouldnt this work?
you could use a database instead of doing what you're doing rn
in the database you would store only the id of the category and every 60 minutes you would fetch the category, clone it, delete the old one and update the id present in the database
using a database would be better because it ensures that a category is cached when the bot starts, it would also save the last category if the Bot crashes so it keeps the cache even if the lifetime period of the bot come to an end (thing that is not possible to do barely using python's runtime cache)
yeah I guess that you could this too but you need to iterate trough all the channels of the guild
but what if the category was renamed by an admin?
or what if there's another category/channel with the same name?
names aren't unique
ill amke sure there isnt
for channel in category.channels:
if "「🥥」・chat" in category:```
could i do that
category is an object
/ 🚫 instead of answer with a message yay