#discord-bots

1 messages · Page 213 of 1

slate swan
#

I'd just let user send the tag content as a message
and then make a slash cmd with this syntax
/tag create name:<str> message_id:<str>

#

but that would need fetching the message, bad idea.

hushed galleon
#

i think taking a message link would be even more annoying to use

slate swan
#

a pastebin url

smoky sinew
#

what was the field to get the value of the interaction response btw

hushed galleon
#

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?

smoky sinew
#

from send_message specifically

hushed galleon
#

!d discord.Interaction.original_response

unkempt canyonBOT
#

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.
smoky sinew
#

thanks

slate swan
#

is it just me or discord doesnt allow using slash commands while replying to a message?

smoky sinew
#

are those comparable with normal messages

#

using __eq__

smoky sinew
#

unless they're somehow different

slate swan
#

im talking about app commands from bots, not the default ones

hushed galleon
#

it inherits from Message and doesnt override eq so likely yes

smoky sinew
#

ok cool

smoky sinew
#

i think it has worked for me in the past though with bot slash commands

slate swan
#

normal

smoky sinew
#

what's a better name, /tag remove or /tag delete

slate swan
#

when replying

slate swan
smoky sinew
#

ohh

#

i spend more on the embed design than on the actual code to be honest

shrewd apex
slate swan
#

and i just dont code

shrewd apex
#

sarth now busy with laif

slate swan
shrewd apex
#

got some commitments cough

slate swan
#

yes, JEE in 25 days

shrewd apex
slate swan
#

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?

shrewd apex
slate swan
slate swan
#

what are you gonna use the time module for?

shrewd apex
slate swan
shrewd apex
#

are something is there tho dont remember

slate swan
#

Guild.get_member

shrewd apex
#

probably yeah

smoky sinew
#

not probably

shrewd apex
#

aight

slate swan
#
@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
smoky sinew
#

there should be try_object functions

slate swan
#

what would that do?

smoky sinew
#

try to get an object from the cache and fetch it if it isn't there

slate swan
#

!d disnake.Client.get_or_fetch_user 🐢

unkempt canyonBOT
#

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.
shrewd apex
#

i mean its just a line

smoky sinew
#

why would i switch to disnake when i could just code my own discord wrapper

slate swan
#

someone could create a PR in the dpy repo but will probably not get accepted

shrewd apex
slate swan
shrewd apex
#

if u had put this effort for jee u would be in iit by now PTK_poliwhirl_eyes

smoky sinew
slate swan
#

i don't use my books often btw

shrewd apex
smoky sinew
#

it's a basic function, honestly it could probably be the default behaviour or get_user even

slate swan
smoky sinew
#

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

slate swan
smoky sinew
#

that is the worst idea bruh

slate swan
#

🗿then create your own fork

shrewd apex
#

just modify dpy lib directly

#

then go try to flex in dpy server pithink

#

life accomplishment

slate swan
#

3rd party code, get rekt

smoky sinew
#

instant ban lol for discussing forks

shrewd apex
vital glacier
#

    @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.

woeful magnet
#

I wanna know how to run multiple Discord clients simultaneously

naive briar
#

Why

vital glacier
dense jackal
#

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

unkempt mauve
#

I want to make a info channel cmd. What is the class for channel?>

#

Ok I got it

shrewd apex
dense jackal
#

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)```
shrewd apex
#

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 loooli

dense jackal
#

A friend did it for me

#

But they dont wanna help me no more unfortunately HuTaoCry HuTaoCry

#

Why?

shrewd apex
#

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

shrewd apex
dense jackal
shrewd apex
dense jackal
#

Does my code contain something suspicious?

shrewd apex
#

i dont know i generally don't open pastebin on phone it freezes the screen

dense jackal
#

How did you know I didnt code that then

shrewd apex
#

list.append

#

anyone who can make a view or dm ticket system this far wont make such a rookie mistake

dense jackal
#

Ah lol

#

Yeah im kinda stuck there now

shrewd apex
#

is the view persistent?

dense jackal
#

They explained something to my that I was close to understand

#

But now your telling me that was completely wrong

shrewd apex
#

like does it work even after u restart the bot?

dense jackal
shrewd apex
#

do the buttons in the ticket work after u restart the bot

dense jackal
#

No

shrewd apex
#

lmao rip

dense jackal
#

Says interaction failed

#

That’s in dms btw

#

No tickets

#

That’s basically to create a ticket

shrewd apex
#

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

dense jackal
#

Smh

shrewd apex
#

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)
dense jackal
#

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)```
shrewd apex
#

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

dense jackal
#

What does return do btw

shrewd apex
#

i mean thats probably the best i can do without a good database system

shrewd apex
dense jackal
#

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?

dense jackal
shrewd apex
#

sup

shrewd apex
#

micro optimisations pikachu_sip

woeful magnet
#

#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 = "..."

shrewd apex
#

getting chat gpt vibe

woeful magnet
#

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?

shrewd apex
#

chat gpt confirmed brainmon

woeful magnet
#

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

shrewd apex
#

its not as much as debug here its to rewrite the code

shrewd apex
vale wing
#

discord.Intents.all() is a classmethod btw

shrewd apex
#

hmm seems like he is trying to run multiple bots via a few commands and on_ready

vale wing
#

@shrewd apex mm there's client.run(bot=False) 💀

shrewd apex
vale wing
#

The point is it's a selfbot

#

@shrewd apex come to bobux there's funny screenshot

shrewd apex
smoky sinew
#

bobux

fresh fern
#

how to edit a response from the bot (InteractionResponse)

smoky sinew
#

await interaction.edit_original_response?

fresh fern
#

didnt work

#

nope

naive briar
#

Saying it didn't work doesn't explain the problem

fresh fern
#

oh

#

i tried everything

#

please help

naive briar
#

You didn't even explain your problem

fresh fern
#

i want to edit the message and send "TIMEOUT" after timeout

#

in view

smoky sinew
fresh fern
#

i tried

smoky sinew
#

and what happened

fresh fern
#

nothing

smoky sinew
#

??

fresh fern
#

the event is on_timeout?

#

right

smoky sinew
#

event of what

fresh fern
#

of timeout

smoky sinew
#

bruh

fresh fern
#

huh!!?

lyric latch
#

can any one help me out

#

like how to print, items of same keys in a dict

#
dict = {
  "a" : "letter 1",
  "a" : "letter 2"
}
smoky sinew
lyric latch
#

is this even possible

smoky sinew
#

dicts cant have same keys

#

they have to be unique

lyric latch
lyric latch
#

thanks buddy

shrewd apex
#

!d discord.ui.View.remove_item

unkempt canyonBOT
#

remove_item(item)```
Removes an item from the view.

This function returns the class instance to allow for fluent-style chaining.
slate swan
#

!d nextcord.ui.Select

unkempt canyonBOT
shrewd fjord
scenic brook
#

Hi, with discord.py it's possible to add a commande here ?

#

And it's possible have a field like this ?

vocal snow
#

Yes, they are called Slash Commands

scenic brook
#

ok thx

radiant bough
#

What do I do to replace the ‘ with , and mention all the roles?

slate swan
#

!d str.replace

unkempt canyonBOT
#

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.
slate swan
#

Might be useful

radiant bough
slate swan
#

You only have the name of the role?

radiant bough
#

Yea

unkempt canyonBOT
#

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.
vale wing
#

If that is a list

radiant bough
#

I did this..

slate swan
#

!d discord.utils.find

unkempt canyonBOT
#

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.
slate swan
#

Look at this example of finding a Member with name

#

And try to convert it to finding a Role with name

radiant bough
#

role = discord.utils.find(lambda r: r.name == “role”, ctx.guild.roles)

Would work?

vale wing
#

Eh wait what input data do you have and what output do you want to get

radiant bough
#

nvm

unkempt canyonBOT
#

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...
shrewd apex
slate swan
#

👀

vocal snow
#

league :P

radiant bough
#

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

slate swan
#

Just compare before.roles with after.roles and you can figure out which roles were added/removed

upbeat otter
karmic nimbus
# slate swan Just compare `before.roles` with `after.roles` and you can figure out which role...
@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💀

vocal snow
#
async def on_member_update(before, after):
``` your function signature should just have two positional parameters
#

both of which are discord.Member objects

karmic nimbus
#

then what should i do with that

vocal snow
#

yes, if you haven't used functions before I would highly recommend learning them

upbeat otter
unkempt mauve
#

how do I access the everyone role for overwriting

karmic nimbus
#

ok thx

upbeat otter
unkempt canyonBOT
upbeat otter
#

or you can usr the guild id itself

maiden fable
#

Finally, the mods do be testing if reactions should be enabled again in this channel

velvet compass
#

I've seen one in the last 12 hours

maiden fable
#

Prolly cz most of the ppl dk about it

vocal plover
#

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

velvet compass
#

I mean, we still don't want to be bothered to moderate them

vocal plover
#

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

maiden fable
#

alec, the shrug slash command should be at the start of the message

#

But yea, u r right

velvet compass
#

I'm happy to give it a trial, it doesn't hurt to try things out and see what happens

vocal plover
maiden fable
#

Hahaha

stark ingot
#

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.

maiden fable
#

If u want a different lib, there is hikari

smoky sinew
#

reactions

#

very interesting

vocal plover
#

+1 for nextcord/disnake in the description or a pin with lib alternatives kek

slate swan
#

i can finally react with Flantic_yes / 🚫 instead of answer with a message yay

#

no im not lazy

vocal snow
vocal plover
smoky sinew
#

what's a good permission for deleting tags

#

manage server?? manage messages?

#

it will all be configurable anyways

vocal plover
#

I'd probably default it to manage server

#

better to default to a higher permission level if you're unsure, generally

smoky sinew
#

that's what i thought

smoky sinew
#

how do i get the number of chunks with as_chunks

hushed galleon
#

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)

smoky sinew
#

i just ended up doing list(chunks)

#

i thought it always returned an iterator of the same type

hushed galleon
#

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

smoky sinew
#

so it's not safe to do that

#

?

hushed galleon
#

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

brazen raft
smoky sinew
#

but wouldn't as_chunks return a list if it was given a list

hushed galleon
#

oh nope its always an iterator

unkempt canyonBOT
#

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]]:
    ...```
cold sonnet
#

since when can I do that

#

Oh I've been able to do that for an hour and 55 minutes

#

no, longer

white citrus
#
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'
slate swan
#

show code

white citrus
slate swan
#

oh sorry i didnt see the link lol

#

!d nextcord.ui.StringSelect.options

unkempt canyonBOT
slate swan
#

and your nextcord seems to be outdated ( it's StringSelect now, not Select )

white citrus
slate swan
#

yes

white citrus
#

self.children should be the dropdown

#

I want to update the dropdown lol

slate swan
#

when you're in the select class, self represents the Select which doesnt have a children attribute

#

view has that attr

white citrus
#

Okay so how can i get the attr in there

#

Or how can i edit the dropdown else?

slate swan
#

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

slate swan
slate swan
#

yes and then a single command that would get the discord users username

white citrus
slate swan
slate swan
white citrus
#

I want to edit it after a select

smoky sinew
#

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

white citrus
slate swan
#

how would i get the username of a user?

unkempt canyonBOT
slate swan
smoky sinew
#

you shouldn't use their username to save because it can change

#

use their ID instead

slate swan
#

ok so how would i get the id?

smoky sinew
glad cradle
#

docs are cool

slate swan
#

ok so for example i would do

pl.id = user.id
smoky sinew
#

what

#

what is pl

white citrus
#
  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
slate swan
#

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

white citrus
#
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")```
slate swan
#

but what if i wanted to send a message saying hello <insert username> when they start the game?

smoky sinew
#

24 hour slowmode?

unkempt canyonBOT
#
Format-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.

smoky sinew
#

f"Hello, {user}"

smoky sinew
#

what does your code look like

#

are you using a self-bot

exotic maple
smoky sinew
#

you leaked your token in the screenshot

exotic maple
#

but can you help

#

it keeps saying invalid token

#

but its a correct token

smoky sinew
#

how'd you copy the token

exotic maple
#

using the copy button on the developer portal

smoky sinew
#

can someone help with this i have a SQL table which has created_at set to DEFAULT NOW() AT TIME ZONE 'utc'

unkempt canyonBOT
#

leaf/extensions/tags.py line 272

value=discord.utils.format_dt(tag_record["created_at"], "D"),```
smoky sinew
#

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

astral ether
#

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}')
slate swan
#

!d discord.Guild.create_text_channel

unkempt canyonBOT
#
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...
slate swan
#

you can pass category argument

astral ether
astral ether
slate swan
#

code?

astral ether
#
channel = await ctx.guild.create_voice_channel(name=f'{msg.content}', category=1023283647006134364)
slate swan
#

you need to pass CategoryChannel object not id of category

smoky sinew
slate swan
#

!d discord.utils.find

unkempt canyonBOT
#

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.
smoky sinew
#

why

slate swan
#

use this to find a category

smoky sinew
#

no

#

just use get_channel

slate swan
#

category is treated as channel?

smoky sinew
#

yup

slate swan
#

then use get_channel

astral ether
slate swan
#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
slate swan
#

do this ```py
category = bot.get_channel(id)

slate swan
#

which you can get using code i sent above

astral ether
astral ether
slate swan
#

its bot.get_channel

#

not ctx

astral ether
#

ho ok 🤦‍♂️

#

yes he work thanks !

slate swan
#

👍

white citrus
#

how can I get the missing permission out of missing permissions

glad cradle
smoky sinew
#

it's get_channel

white citrus
smoky sinew
white citrus
smoky sinew
#

wdym?

white citrus
#

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```
smoky sinew
#

that's not MissingPermissions though

#

that's just forbidden

#

you can handle that with try/except

white citrus
#

At which point?

#

I updated nextcord and now this comes up @smoky sinew

smoky sinew
#

when the exception occurs

#

missing permission bot.return?

#

what does that mean

smoky sinew
#

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..

silk fulcrum
#

Slash commands?

#

Disorientation?

glad cradle
smoky sinew
silk fulcrum
#

I mean you just said it doesn't work without giving any details so I have to guess I guess

glad cradle
regal cove
#

Why do my buttons stop working after around 15 minutes? Is there Any way of fixing that?

smoky sinew
slate swan
#

how to run discord bot with database for free

smoky sinew
whole shoal
shrewd apex
#

hmm

regal cove
smoky sinew
#

add custom_id to all items, set timeout to None, and add the view in setup_hook or somewhere else

#

no

white citrus
#

What is with_message at await interaction.response.defer()

slate swan
tired pollen
#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

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...
tired pollen
#

ah?

slate swan
worthy heart
#

hello, where can I find docs for using slash commands with discord.py (import discord)

cloud dawn
worthy heart
cloud dawn
#

!d discord.app_commands.Command

unkempt canyonBOT
#

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")...
worthy heart
#

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)

full lily
worthy heart
#

idk, it felt kinda slow

smoky sinew
worthy heart
worthy heart
#

how can I change the bot's status?

slate swan
unkempt canyonBOT
#

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...
graceful ermine
#

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?

thin raft
#

loop through all members every x

slate swan
#

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

slate swan
thin raft
#

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

slate swan
#

right we need to create some cache thingy

thin raft
#

basically

#

you could just use a json file with a list

#

or even a txt file with the ids separated by a space

slate swan
#

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

unkempt canyonBOT
#
Bot variables

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!

smoky cedar
#

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?

slate swan
smoky cedar
#

Yeah

slate swan
#

then you need to add it in code

smoky cedar
#

I have bot = discord.Client(intents=discord.Intents.default()) which I believe is correct for messaging intent

slate swan
#
intents = ...
intents.message_content = True```
smoky cedar
#

But I need to refresh it or something internally no?

#

Ah its not on by default

slate swan
#

yes its not on

#

so you need to define intents before client

#

then enable intent you want

#

then pass the intents varriable to Client

brisk rapids
#

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

sick birch
slate swan
#

how does the signupButton looks like

brisk rapids
#
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)
slate swan
#

so you accept interaction inside __init__ method

#

which you dont want here

#

just remove interaction argument from init

worthy heart
#

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
slate swan
#

you are missing this import from discord import app_commands

smoky sinew
slate swan
smoky sinew
#

cache them and loop over the cached bot members

#

instead of always looping through the full member list'

brisk rapids
#

Now im getting the error: TypeError(f'expected an instance of View not {view.class.name}')
for the line

self.add_view(signupButton())
slate swan
#

could be but what if you add a bot to a server while its going

smoky sinew
#

i'm assuming he's just making an uptime command for a certain amount of fbots

brisk rapids
#
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)
slate swan
#

not Button

#

View can hold a Button as item

brisk rapids
#

so I should change discord.ui.Button to discord.ui.View?

slate swan
smoky sinew
#

try something like this and use button as a decorator

smoky sinew
#

someone review pls

flint heart
#

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])

sick birch
smoky sinew
flint heart
flint heart
gaunt spear
#

why the errors?

slate swan
#

Why not upgrading to latest?

smoky sinew
smoky sinew
slate swan
#

lol

#

But why do you know that

smoky sinew
#

😳

#

because i read the 2.0 changelog

#

(im a nerd and i actually read changelogs)

slate swan
#

Dam

flint heart
#

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)

smoky sinew
smoky sinew
#

you should just use await bot.close()

flint heart
#

Alr, thx

gusty flax
#

YOOO

#

WE GOT REACTIONS

gusty flax
gaunt spear
smoky sinew
slate swan
#

i think its been there for a longer time

#

!d discord.Member.display_avatar

unkempt canyonBOT
#

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.
slate swan
#

oh nvm it was only display_name then

gaunt spear
#

i thought it was already a thing

young dagger
#

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
gusty flax
young dagger
gusty flax
young dagger
rigid hare
#

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
gusty flax
#

R u saying that per task, u want a way to see if its done or not?

young dagger
# gusty flax ```py global verification_task```

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?

gusty flax
young dagger
young dagger
#

!e

global verification_task

print(verification_task)```
unkempt canyonBOT
#

@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
#

hm

#

!epy global verification_task = False print(verification_task)

unkempt canyonBOT
#

@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
gusty flax
#

globals are annoying to use lowkey

#

I just use classes and have attributes.

#

Tho Im not sure what ur trying to do.

young dagger
# gusty flax 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 ...
gusty flax
young dagger
#

So if verification_task is not true it should execute the code

#

in client.event

gusty flax
young dagger
#

No its greyed out

gusty flax
young dagger
gusty flax
#

!pastebin

unkempt canyonBOT
#
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.

young dagger
gusty flax
young dagger
gusty flax
# young dagger

Thats true, it is in local scope. U would have to use global

young dagger
#

Or am I wrong?

gusty flax
#
verification_task = False
@tasks.loop(hours=24)
async def update_elo_ratings():
    global verification_task
    verification_task = True```
#

This shld work

young dagger
# gusty flax 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 ...```
gusty flax
#

sry i dont use globals that much. i forgot how they work 😓

young dagger
#

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?

gusty flax
#

Thast why most ppl use classes, with attributes. Generally, globals aren't suggested.

young dagger
#

It seems like it can read it without declaring it as global

#

Can somebody else please confirm?

young dagger
#

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

gusty flax
#

💀 I want to see which value ur talking about. It is much easier to help seeing the code.

gusty flax
young dagger
gusty flax
#

!e```py
boolean = False

def myfunc():
global boolean
boolean = True

def checker():
global boolean
print(boolean)

print(boolean)
myfunc()
print(boolean)
checker()```

unkempt canyonBOT
#

@gusty flax :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | False
002 | True
003 | True
gusty flax
#

!e```py
boolean = False

def myfunc():
global boolean
boolean = True

def checker():
print(boolean)

print(boolean)
myfunc()
print(boolean)
checker()```

unkempt canyonBOT
#

@gusty flax :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | False
002 | True
003 | True
gusty flax
#

its the same

#

seems that u can access it but not reassign it unless u access the global

young dagger
echo wasp
#

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}")

vale wing
#

@young dagger you need to declare variable as global if it is redefined in function scope

vale wing
# echo wasp hi, I am dealing with requests and the bot returns 403 when you can access it no...
  1. You are most likely missing authorization header. Read about authorization on docs of API you are using
  2. 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 😇

echo wasp
vale wing
junior drum
echo wasp
vale wing
junior drum
#

a okay so i should rely on amazon

#

thanks

vale wing
#

Good idea

junior drum
echo wasp
junior drum
#

like i have to sit for around 5 mins with a blank console

vale wing
junior drum
#

could be

echo wasp
vale wing
#

Like ofc I can go to google, find its docs and send the link to you but I think it's not that hard

vale wing
#

If you have any struggles tell me tho

echo wasp
echo wasp
echo wasp
smoky sinew
#

use aiohttp instead

echo wasp
vale wing
#

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

echo wasp
vale wing
#

"has args and kwargs very similar"

echo wasp
slate swan
#

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>```
naive briar
#

What? I see no error

#

!traceback

unkempt canyonBOT
#
Traceback

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.

slate swan
echo wasp
echo wasp
slate swan
#

its returning this since i put it in a try method

#

and i made it print out the error

echo wasp
slate swan
vale wing
slate swan
# vale wing 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)```
vale wing
#

Exceptions just don't look like that

slate swan
naive briar
#

Don't handle exceptions at that point

slate swan
#

dont know why tbh

vale wing
#

And see if it is really printed there

echo wasp
#

remove the try and except and try again

vale wing
#

Actually um guild = discord.Guild bruh

#

You are assigning class to a variable

echo wasp
vale wing
naive briar
#

Wth, I didn't even notice that

#

!d aiohttp.ClientResponse

unkempt canyonBOT
#

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).
vale wing
#

@echo wasp this class's methods

slate swan
vale wing
slate swan
#

hmm interesting, ill look into it

echo wasp
#

how do i add a auth header

echo wasp
slate swan
echo wasp
slate swan
# echo wasp 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)```
echo wasp
slate swan
echo wasp
slate swan
#

alright

#

keyerror now @echo wasp

echo wasp
slate swan
#

do i set the guild id in the db as an int aswell?

#

OH I THINK I KNOW WHAT I DID WRONG

echo wasp
#

please remove your guild id from the discord messages!

#

now!

slate swan
echo wasp
#

it is a security issue

slate swan
#

ah

#

there we go

echo wasp
echo wasp
slate swan
#
ValueError: invalid literal for int() with base 10: 'channel'```
echo wasp
#

why is channel in quotes?

#

if chnnel is already a int/

slate swan
#

ah wait i think i know

echo wasp
slate swan
#

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

echo wasp
#

did it work?

echo wasp
vale wing
echo wasp
#

That returns a 403 forbidden

vale wing
#

What API are you using

echo wasp
#

But if it's off its a 200 and aiohttp like you told me to use

echo wasp
vale wing
#

That's not an API

#

What URL are you making requests to

vale wing
smoky sinew
echo wasp
vale wing
#

I think so-called protection is basically authorization, not sure what they're trying to do tho

vale wing
echo wasp
#

Basicly, pinging a site

vale wing
#

Bru

echo wasp
#

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

vale wing
echo wasp
vale wing
#

If site does not belong to you to obviously can't

echo wasp
#

Because services like better uptime gets past it.

vale wing
#

🧐

#

I don't understand the expected output, input and whole purpose of this

echo wasp
echo wasp
vale wing
echo wasp
#

Thanks

bronze whale
#

Yo

tacit phoenix
#

anyone know how to make talk bot

shrewd apex
#

just use some api like chat gpt and u are good to go

#

!pypi chatterbot if ur looking more long term

unkempt canyonBOT
tacit phoenix
#

oh ty

ruby tendon
#

you want at least a gpt level bot that one is pretty old

vale wing
#

Train own model with tensorflow 🤓

ruby tendon
#

I'm making one with the llama model and there are a few on github

vale wing
#

You will need uh text vectorization, embedding and some RNN layer

shrewd fjord
slate swan
#

It doesn't work properly.

slate swan
junior drum
#

is client.logout() a thing?

young dagger
#

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']```
naive umbra
unkempt canyonBOT
#
Noooooo!!

No documentation found for the requested symbol.

naive umbra
#

question answered

#

logout is only available in earlier version afaik

#

now it's

#

!d discord.Client.close

unkempt canyonBOT
#

await close()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Closes the connection to Discord.
junior drum
#

a okay

#

then i assume there must be a start function too?

naive umbra
#

yup

#

!d discord.Client.start

unkempt canyonBOT
#

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").
junior drum
#

ah ty

young dagger
#

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```
slate swan
#

!e ```py
def f():
print("Hello")
return
print("World")
f()

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello
young dagger
#

lp should not be included

slate swan
#
tier_and_rank = await get_tier_and_rank(summoner_id, RIOT_API_KEY)[:-1]
young dagger
slate swan
#

use this to do that

#

!d str.join

unkempt canyonBOT
#

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.
young dagger
# slate swan !d str.join

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}"```
slate swan
#

try

shrewd fjord
#

Or simply return a list
return [tier, rank, lp]

young dagger
shrewd fjord
#

Idk what are you trying to do tho

young dagger
#

For this example, I only want to update the user's tier and rank in the database without including LP

shrewd fjord
shrewd fjord
#

But rn you want to fetch 2 of them?

young dagger
young dagger
# shrewd fjord But rn you want to fetch 2 of them?
                # 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}})```
shrewd fjord
#

return [tier, rank, lp]

t_a_e=f"{tier_and_rank[0]} {tier_and_rank[1]}"

pale escarp
#

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

shrewd fjord
#

Ugh

#

!d discord.ext.commands.Bot.add_cog

unkempt canyonBOT
#

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...
shrewd fjord
pale escarp
#

yea i figured but when i try to make it await i get a lot of errors.

shrewd fjord
#

so technically
async def setup(bot):
await bot.add_cog(....)

pale escarp
#

ty i think thats what i done but let me try again

shrewd fjord
#

Ig

shrewd fjord
pale escarp
#

isn't bc bot.add_cog is not await? or something diff

shrewd fjord
shrewd fjord
#

So await is must

pale escarp
#

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

shrewd fjord
#

Add all codes to a async function then just ah do asyncio.run()

#

Or do it on setup_hook or on_ready

pale escarp
#

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())```
slate swan
#

I created a bot.wait_for('reaction_add')
how can i get the name of the user who clicked the reaction ?

sick birch
slate swan
#

thanks

slate swan
#

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 🙏.

fast musk
#

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

glad cradle
slate swan
glad cradle
fast musk
slate swan
#

i must add the intents.reactions ?

glad cradle
slate swan
glad cradle
#

otherwise your bot isn't able to receive on_reaction_add events and so it can't update its cache

pale escarp
glad cradle
slate swan
vital glacier
#

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

glad cradle
fast musk
#

have you tried printing just the exception message? Assuming it is generic?

glad cradle
unkempt canyonBOT
vital glacier
#

oh

glad cradle
#

when a MissingPermissions error is raised you can access the missing_permissions attribute

vital glacier
#

alright but the error basically displays as ['ban_members'] how do i remove the [' '] from the message

#

lol

glad cradle
#

this is a basic python knowledge

you can use the join method

#

!d str.join

unkempt canyonBOT
#

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.
vital glacier
#

oh so that would work

#

ight good to know

vocal snow
#

or if it's just the first item of the list, just use it's index

shrewd apex
#

@vocal snow wanna join pyweek?

vocal snow
shrewd apex
#

we make games using python

glad cradle
#

I think he's sarcastic

shrewd apex
smoky sinew
smoky sinew
#

bet

#

who else is in

shrewd apex
#

me sarth n snipy

smoky sinew
shrewd apex
smoky sinew
#

yeah 100%

shrewd apex
#

yeah server

smoky sinew
#

ok dm me the invite

slate swan
#

i wish i ever touched pygame

#

algum br?

#

que saiba python

karmic nimbus
#

Is it possible to get someone's nickname history?

copper bobcat
#

pls help me for this

shrewd apex
shrewd apex
copper bobcat
shrewd apex
#

discord.py has everything interaction slash commands buttons and stuff

copper bobcat
#

What should I do?

shrewd apex
#

ur code what do i know replace discord components with discord.py

#

discord components is a third party outdated library

copper bobcat
#

ok tnx

tough lance
#

Hi, how can I get whole traceback as string?

keen talon
keen talon
junior walrus
#

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?

shrewd apex
unkempt canyonBOT
#

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").
tough lance
#

Thanks

left dew
#

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**")```
gloomy owl
#

@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

thin raft
#

!d discord.ext.commands.Bot.fetch_channel

unkempt canyonBOT
#

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.
thin raft
#

maybe that

left dew
# thin raft what's wrong with it

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

slate swan
#

How can i set my bot's discord status using the gateway/api

thin raft
slate swan
#

ah

#

thank you

thin raft
#

np

thin raft
#
@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
left dew
#

should that work?

thin raft
#

:v

left dew
#

ill try

thin raft
#

yup

left dew
# thin raft yup

wait couldn't i just loop through the category and check if a channel with a certain name is there?

slate swan
left dew
#
  for channel in category.channels:
    if "「🥥」・chat" in category:```
left dew
#

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

unkempt canyonBOT
#
Bot variables

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!

thin raft
#

I am storing the new channel

#

so I delete the last new channel

#

and set the variable again to be the new channel

left dew
#

i tried your code but got an error

thin raft
#

I need to see the error for know what's happening

left dew
#
AttributeError: 'MyBot' object has no attribute 'last_channel'```
thin raft
#

oh yeah mb

#

on init set bot.last_channel to None

left dew
#

uhh

thin raft
#

get channel can't take None as an arg?

left dew
#

i dont have an init

thin raft
#

wdym you don't have an init

#

send full code

#

!paste

unkempt canyonBOT
#
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.

left dew
#

my whole code?

thin raft
#

yeah

left dew
#

its 3k lines long

thin raft
#

!discord.ext.commands.Bot.fetch_channel

thin raft
left dew
#

yes

glad cradle
#

!d discord.ext.commands.Bot.fetch_channel

unkempt canyonBOT
#

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.
left dew
#

i dont like cogs

thin raft
#

...

#

you need some organisation man

left dew
#

not if i know where evrything in my code is

thin raft
#

it is.

left dew
#

anyway back to the problem

thin raft
#

the problem rn is your unorganised code

left dew
#

its not

thin raft
#

you should use cogs

left dew
#

thats not affecting my code

#

but i dont want to

thin raft
#

set bot.last_channel to None on init

left dew
#

i dont have an init though

thin raft
#

see how it is an issue

gaunt spear
#

💀

left dew
#

surely theres another way without needing to use init

thin raft
#

yeah, the wrong way

glad cradle
#

he can still configure it as None even without a commands.Bot subclass

thin raft
#

he needs to get track of it

glad cradle
#

just add
MyBot.last_channel = None right after the definition of MyBot

thin raft
#

doesn't feel right 💀

naive umbra
#

it should, because that's totally valid

glad cradle
#

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
naive umbra
#

similarly, you don't inherit discord.Intents just to override the default attributes
you do

intents = discord.Intents.default()
intents.message_content = True
etc...
left dew
#

AttributeError: 'NoneType' object has no attribute 'id'

thin raft
#

instead of storing a discord.TextChannel store an int

glad cradle
left dew
#

oh

#

if it isnt none the channel purges?

glad cradle
#

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)

left dew
#

i just want it to delete a channel every hour and remake it

glad cradle
#

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

left dew
#

oh

#

im not sure how to cache

glad cradle
#

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)

glad cradle
#

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

left dew
#

ill amke sure there isnt

#
  for channel in category.channels:
    if "「🥥」・chat" in category:```
#

could i do that