#discord-bots

1 messages ยท Page 260 of 1

vocal snow
#

๐Ÿ—ฟ

#

im going to start spoonfeeding everryone

sonic vapor
#

๐Ÿ—ฟ

slate swan
#

ok

naive briar
sonic vapor
#

it work๐Ÿฅน

slate swan
#

look what magic happens when you do what it tells you to do

cloud dawn
vocal snow
#

everyone except you

slate swan
#

!d discord.abc.Messageable.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
slate swan
#

there is stickers kwarg

hasty pike
#

Tf bro?

#

Language

sonic vapor
#

anything change in the code

slate swan
sonic vapor
hasty pike
#

Who's Hindi speaker i might provide support as i know language?

slate swan
sonic vapor
#

kuch ni

#

no bro

#

bot banana hai

hasty pike
cloud dawn
#

Guys english please, else use DM.

sonic vapor
#

arre help kar

slate swan
#

i belive you need to speak english here

sonic vapor
#

who is this @hasty pike

slate swan
#

!rule 4

unkempt canyonBOT
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

sonic vapor
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

hasty pike
daring olive
#

yes please, using english is a requirement here

hasty pike
#

Sorry my bad

sonic vapor
cloud dawn
#

Minaa, :3
Been awhile.

sonic vapor
#

from where you are

hasty pike
sonic vapor
#

@hasty pike indian?

hasty pike
#

Please stick to the topic

sonic vapor
#

i want to add economy feature

#

how?//

hasty pike
#

Please specify your question

slate swan
#
  • setup a database
  • connect to it in python
  • create a querry to add coins
  • create a querry to remove coins

in most simple terms

slate swan
#

you tried many times what

sonic vapor
slate swan
#

well im not as good in databases

hasty pike
slate swan
hasty pike
cloud dawn
#

Use Docker for that.

hasty pike
slate swan
cloud dawn
sonic vapor
#

i need a patner for making bot

sonic vapor
slate swan
hasty pike
cloud dawn
# sonic vapor what is docker?

Docker is a tool for developers to quickly create containerized virtualizations of an os in order to create a good environment for developing.

slate swan
#
Docker is a set of platform as a service products that use OS-level virtualization to deliver software in packages called containers
slate swan
#

its good when you want your code to work the same on each machine

cloud dawn
formal basin
#
@tasks.loop(minutes=15)
async def guild_count():
    await client.change_presence(activity=discord.Activity(type = discord.ActivityType.watching, name=f'{len(client.guilds)} servers | type /help or /info'))
    print(f"guild count is {len(client.guilds)}")

@guild_count.before_loop
async def before_count():
        print('waiting...')
        await client.wait_until_ready()
``` is this code right?
sonic vapor
#

ah docker=590mb

#

๐Ÿ˜ข

cloud dawn
#

Docker is a lot larger than that if you are planning to work with it.

sonic vapor
#

should i ingnore it?

formal basin
#

so I dont think it is working

winter token
#

can someone explain me these lines duration_regex = r'(\d+)([hms])' duration_values = re.findall(duration_regex, duration_str)

cloud dawn
formal basin
cloud dawn
hasty pike
cloud dawn
hasty pike
formal basin
winter token
hasty pike
formal basin
#

at the bottom

cloud dawn
formal basin
#

and my task is at the top

winter token
formal basin
cloud dawn
#

This in particular tries the match any digit after the letters h, m or s

hasty pike
winter token
#

ig I should learn abt re module a bit more

hasty pike
#

@sonic vapor pick request

cloud dawn
cloud dawn
slate swan
#

So I am trying to make a discord bot. The command is /locate and I want it to be shown like the image I attatched. I also want the user to input a "player_gamertag" into the box as shown by the picture. How can I d this?

intents = discord.Intents.default()
bot = commands.Bot(command_prefix="/", intents=discord.Intents.all())

@bot.command(name='locate')
async def locate(ctx, player_gamertag):
cloud dawn
slate swan
cloud dawn
cloud dawn
slate swan
slate swan
cloud dawn
slate swan
cloud dawn
#

A guild represent what we call a server. Guild is Discord's way of saying that.

slate swan
cloud dawn
#

Yes, that is needed so that the bot knows where to copy the commands to. Otherwise you will register them globally what otherwise can take up to an hour.

#

This way you create a development "guild" so you can use them instantly.

slate swan
#

Okay, I have that part done

cloud dawn
#

Nice! Then you need to fill in your token on the bottom of the script and you can try it out.

slate swan
#

alright

#

@cloud dawn ModuleNotFoundError: No module named 'discord.enums'

cloud dawn
slate swan
#

from typing import Optional

import discord
from discord import app_commands

cloud dawn
#

Yes that is what the script imports, did you install Discord.py or did you install py-cord or nextcord?

slate swan
#

idk

slate swan
cloud dawn
#

Grab your terminal and input some commands for me

slate swan
#

kk

#

which commands?

cloud dawn
#

pip show nextcord && pip show py-cord

#

What does this output?

slate swan
#

both not found

cloud dawn
#

And this? pip show discord && pip show discord.py

slate swan
#

a mesage to long to send here

#

in red

cloud dawn
#

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

fringe lake
#

guys when i hold shift and click on copy message id it gives me something like this:

343944376055103488-1123628370228416593

but when click on the 3 dots and then copy message id it gives me something like this :

1123628370228416593

what is the diffirence between them ?

cloud dawn
cloud dawn
#

@slate swan pip uninstall discord.py && pip install discord.py

#

Try this, just a re-install.

slate swan
#

kk

#

workingnow

#

tysm

#

ill lyk if i have more questions

cloud dawn
#

Oki gl

slate swan
#

pip install -U discord.py shorter

cloud dawn
#

Ty haven't worked with pip in ages

slate swan
#
class MyClient(discord.Client):
    def __init__(self, *, intents: discord.Intents):
        super().__init__(intents=intents)
        # A CommandTree is a special type that holds all the application command
        # state required to make it work. This is a separate class because it
        # allows all the extra state to be opt-in.
        # Whenever you want to work with application commands, your tree is used
        # to store and work with them.
        # Note: When using commands.Bot instead of discord.Client, the bot will
        # maintain its own tree instead.
        self.tree = app_commands.CommandTree(self)

    # In this basic example, we just synchronize the app commands to one guild.
    # Instead of specifying a guild to every command, we copy over our global commands instead.
    # By doing so, we don't have to wait up to an hour until they are shown to the end-user.
    async def setup_hook(self):
        # This copies the global commands over to your guild.
        self.tree.copy_global_to(guild=MY_GUILD)
        await self.tree.sync(guild=MY_GUILD)

Do I need this?

cloud dawn
#

The green stuff? No.

slate swan
#

what green stuff?

cloud dawn
#

The class? Yeah, it's actually recommended to use a subclass. But you can shorten it -> ```py
class MyClient(discord.Client):
def init(self, *, intents: discord.Intents):
super().init(intents=intents)
self.tree = app_commands.CommandTree(self)

async def setup_hook(self):
    self.tree.copy_global_to(guild=MY_GUILD)
    await self.tree.sync(guild=MY_GUILD)
slate swan
slate swan
slate swan
# cloud dawn Sure

yk how some bots it responds and says "only you can see this"

how do I do that?

cloud dawn
#

Just play around with it see what it can do, you can move to a more robust method of "playing around" once you get the hang of it more. You might not reach it but the current API limit of "guild refreshing" is at 1000 times.

cloud dawn
slate swan
cloud dawn
#
# This context menu command only works on members
@client.tree.context_menu(name='Show Join Date')
async def show_join_date(interaction: discord.Interaction, member: discord.Member):
    # The format_dt function formats the date time into a human readable representation in the official client
    await interaction.response.send_message(f'{member} joined at {discord.utils.format_dt(member.joined_at)}', ephemeral=True)
``` Here is an example with the show join date command.
slate swan
#

When I change the command, should I remove ctx?

async def locate(ctx, player_gamertag):

cloud dawn
#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
cloud dawn
#

You can also checkout the docs that also specifies a lot of what I'm saying.

slate swan
#

okay

#

how about ctx?

#

do I remove it?

#

yes but my previous command has ctx

cloud dawn
#

Wups

slate swan
#

async def locate(ctx, interaction: discord.Interaction, first_value: int):

cloud dawn
slate swan
#

or async def locate(interaction: discord.Interaction, first_value: int):

slate swan
slate swan
#

im wondering bc part of the code has await ctx.send

#

and await ctx.author.send

cloud dawn
#

ctx is for messages command and slash commands use interaction.

slate swan
cloud dawn
#

await interaction.user.send("Hi!")

slate swan
cloud dawn
#

Yes since it's embedded in the interaction.

slate swan
#

okay, thx

#

When I do the command, I want it to make it so only you can see this message. And it to say "TorqueBot is thinking."

Then I want it to update once the code is finished to "Check your dms"

cloud dawn
#

Thinking is happening when an interaction could possibly last longer than 3 seconds.

slate swan
#

How do I get it to do that

cloud dawn
#

To ensure this happends you need to defer the command in order to let Discord know you are still processing it.

slate swan
#

await interaction.defer(ephemeral=True)

cloud dawn
#

await interaction.response.defer(ephemeral=True, thinking=True)

#

When responding we respond to the Discord callback. Letting it know we are either finished or still doing something.

slate swan
cloud dawn
#

Let's make a command.

slate swan
#

async def locate(interaction: discord.Interaction, player_gamertag: int):
    await interaction.response.defer(ephemeral=True, thinking=True)
    try:
        if ctx.message.channel.type == discord.ChannelType.private:  # Check if the message channel is a DM
            await ctx.send('My apologies, but you cannot use this command in private messages.')
        else:
            auth_url = "https://x-bot.live/api/postman/auth"
            auth_headers = {"Authorization": api_token}
            auth_response = requests.get(auth_url, headers=auth_headers)
            auth_data = auth_response.json()

            xbl_auth = f"XBL3.0 x={auth_data['userHash']};{auth_data['XSTSToken']}"

            profile_url = f"https://profile.xboxlive.com/users/gt(%7Bplayer_gamertag%7D)/profile/settings"
            profile_headers = {
                "X-XBL-Contract-Version": "2",
                "Authorization": xbl_auth,
                "Accept-Language": "en-US",
            }
            profile_response = requests.get(profile_url, headers=profile_headers)
            profile_data = profile_response.json()

            player_xuid = profile_data["profileUsers"][0]["id"]

            friends_url = f"https://peoplehub.xboxlive.com/users/xuid(%7Bplayer_xuid%7D)/people/social"
            friends_headers = {
                "X-XBL-Contract-Version": "5",
                "Authorization": xbl_auth,
                "Accept-Language": "en-US",
            }
            friends_response = requests.get(friends_url, headers=friends_headers)
            friends_data = friends_response.json()
            friend_count = len(friends_data["people"])
    except KeyError:
        await interaction.response.send_message('Error fetching friends list')

#

await interaction.response.send_message('Error fetching friends list')

When there is a key error I want the message to change to error fetching friends list

#

@cloud dawn Traceback (most recent call last):
File "C:\Users\Josh\Desktop\Improved Locater Bot\v2.py", line 17, in <module>
bot = commands.Bot(command_prefix="/", intents=discord.Intents.all())
NameError: name 'commands' is not defined

cloud dawn
# cloud dawn Let's make a command.

@slate swan ```py
@client.tree.context_menu(name="test defer")
async def test_defer(interaction: discord.Interaction):
await interaction.response.defer(ephemeral=True, thinking=True)

# Processing (Ignore the code)
import asyncio
asyncio.sleep(5)

# End
#####

await interaction.delete_original_response()
await interaction.followup.send(content="Done! Check your DM", ephemeral=True)
slate swan
#

ty

cloud dawn
slate swan
#

ok

slate swan
cloud dawn
slate swan
slate swan
#

Traceback (most recent call last):
File "C:\Users\Josh\Desktop\Improved Locater Bot\v2.py", line 18, in <module>
client = MyClient(intents=intents)
NameError: name 'MyClient' is not defined

vocal laurel
cloud dawn
#

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

vocal laurel
slate swan
vocal laurel
slate swan
#

kk

#

i think ive got it ill lyk

#

@cloud dawn Traceback (most recent call last):
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "C:\Users\Josh\Desktop\Improved Locater Bot\v2.py", line 38, in locate
if interaction.message.channel.type == discord.ChannelType.private: # Check if the message channel is a DM
AttributeError: 'NoneType' object has no attribute 'channel'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'locate' raised an exception: AttributeError: 'NoneType' object has no attribute 'channel'

cloud dawn
#

if issubclass(interaction.channel, discord.DMChannel): # Check if the message channel is a DM

#

This is more specific and doesn't require message intents.

#

Wups hold on don't think this is correct.

#

There edited @slate swan

#

I do recommend testing since I'm coding blind.

slate swan
#

ty

formal basin
#

what is wrong here

cloud dawn
#

!indention

unkempt canyonBOT
#
Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

formal basin
#

my indentition is fine

cloud dawn
#

How so?

#

Your if else is just floating there.

#

Your pass is also not right.

formal basin
#

how?

formal basin
#

please help

#

this makes no sense

slate swan
cloud dawn
#

The code after try isn't the same as anywhere else and above is also really inconsistant.

formal basin
#

nvm

#

I got it

twilit grotto
formal basin
#

my if statement

twilit grotto
#

the entire shit is fucked

#

just fix indentation

formal basin
#

how is there no file

#

its right there

cloud dawn
#

How do you execute your code?

formal basin
cloud dawn
#

Well then it will run main.py right?

thin raft
#

your file is in zagzag/spam.txt

formal basin
formal basin
thin raft
#

and you're accessing ./spam.txt

formal basin
# thin raft and you're accessing `./spam.txt`
Traceback (most recent call last):
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "/Users/zagzag/vscode/zagzag/zagzag.py", line 694, in message
    file.writelines(f"{str(message.author.id)}\n")
ValueError: I/O operation on closed file.
#

what is this error

#

my file is closed?

unkempt canyonBOT
#
Opening files

The built-in function open() is one of several ways to open files on your computer. It accepts many different parameters, so this tag will only go over two of them (file and mode). For more extensive documentation on all these parameters, consult the official documentation. The object returned from this function is a file object or stream, for which the full documentation can be found here.

See also:
โ€ข !tags with for information on context managers
โ€ข !tags pathlib for an alternative way of opening files
โ€ข !tags seek for information on changing your position in a file

The file parameter

This should be a path-like object denoting the name or path (absolute or relative) to the file you want to open.

An absolute path is the full path from your root directory to the file you want to open. Generally this is the option you should choose so it doesn't matter what directory you're in when you execute your module.

See !tags relative-path for more information on relative paths.

The mode parameter

This is an optional string that specifies the mode in which the file should be opened. There's not enough room to discuss them all, but listed below are some of the more confusing modes.

'r+' Opens for reading and writing (file must already exist)
'w+' Opens for reading and writing and truncates (can create files)
'x' Creates file and opens for writing (file must not already exist)
'x+' Creates file and opens for reading and writing (file must not already exist)
'a+' Opens file for reading and writing at end of file (can create files)

thin raft
#

you're using r+ operation

formal basin
#

oh

thin raft
#

just do w

#

that will erase file content

cloud dawn
#

You are trying to modify the file outside of the context.

#

Has nothing to do with the r+ operator.

#

file.writelines(f"{str(message.author.id)}\n") is outside of the context but you still try to do operations on the file.

crimson horizon
#

Hi guys, I made a bot and it needs to send some files in a channel plus in the users dms. Whatever I put first in the code works. for the second one, it just sends it as a file that is not available

#
        files = [nextcord.File(generated_image, filename=f"FreeAI_{i+1}.png") for i, generated_image in enumerate(generated_images)]
        await channel.send(f"{member.mention}\n**{prompt}**", files=files)
        await member.send(f"Your generated images are ready!\n**{prompt}**", files=files)
#

@formal basin

#

(sorry for ping)

naive briar
#

Then why would you ping them

crimson horizon
#

Cause he just helped someone 20 mins ago

naive briar
#

They were helped

crimson horizon
#

oh sorry

#

my bad

proper thicket
#

can someone help me with this error

thin raft
#

show full code

naive briar
#

Oh, yeah

proper thicket
#

2023-06-28 12:47:21 ERROR discord.ext.tasks Unhandled exception in internal background task 'change_status'.
Traceback (most recent call last):
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/tasks/init.py", line 239, in _loop
await self.coro(*args, **kwargs)
File "/Users/hervans/Downloads/Hervy bot/main.py", line 16, in change_status
await bot.change_presence(activity=discord.Game(next(bot_status)))
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/client.py", line 2040, in change_presence
await self.ws.change_presence(activity=activity, status=status_str)
AttributeError: 'NoneType' object has no attribute 'change_presence'

crimson horizon
#

generated_images are the images to send

naive briar
#

The discord.File object isn't supposed to be used more than once, anyways

proper thicket
#

may someone help with my error above.

crimson horizon
slate swan
#

discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.add_money' raised an error: TypeError: object NoneType can't be used in 'await' expression

slate swan
#

thanks

turbid condor
proper thicket
turbid condor
#

Tbh the error is pretty clear

#

Check the docs there is an example on how to set a presence

#

That should help u understand what u did wrong

sick birch
#

Which means you're trying to change the bot's presence before the bot is ready

proper thicket
proper thicket
sick birch
hasty pike
slate swan
#

Masked links are bacc

#

(in 5% of guilds KEKW)

slate swan
#

CS_pepehmm no

#
#

this domain exists huh

slate swan
#

any errors?

#

You have an error in the console you probably don't give

#

not possible

#

Consider using

channel = client.get_channel(...) or await client.fetch_channel(...)
#

Then you have an error handler eating your errors

#

can you print channel varriable to console

#

there is second part

slate swan
#

The or is not there for you to choose, it's a logical or

#

It's one valid line

#

if .get_channel doesnt find the channel in the cache it will fetch it from the api

#

First it tries get_channel if it returns None it will use fetch_channel

#

And if it returned None, you'd have an error - which you're likely eating because of an error handler

#

!e ```py
print(None or "valid channel")
print("valid channel" or "another valid channel")

unkempt canyonBOT
#

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

001 | valid channel
002 | valid channel
slate swan
#

if the first value it truthy it will use it

#

else it will use second option

#

you dont need to check if channel exists now when you are using .fetch_channel

#

the if most likely always will be True unless you paste wrong channel id but it will throw error anyways

#

I'd be nice to share the entire file

#

any error handlers?

#

im asking if you defined any error handlers in code

#

Yeah, then you likely have an error handler making all your errors ignored

#

So look at your code for such an error handler

#

why dont you just disable it for dev purposes

#

ctrl + f -> search for error

#

Then find it, you may also want to consider using cogs

slate swan
#

no you type error only

#

... for real? Never used ctrl+f in your life Bruh

#

it will show you all occurances of the error word in the file

#

It's the same

#

Just for one file instead

#

you said there is error handler and now there is not

#

Well you definitely have something

#

is it your code

#

Find the error handler

slate swan
#

Is it your code

#

Then unless you have serious memory issues, you'd know how an error handler looks like, as well as where it is

#

No, not in 6 days

shrewd apex
#

hmm 200 line per day avg pithink pick up speed when?

slate swan
#

If you really have forgotten then consider going to the doctor to be fair, such memory losses are probably serious

#

oh my fucking god

shrewd apex
slate swan
#

So it's not your code, don't lie lmfao

shrewd apex
#

gimme an example

slate swan
#

No, it's not

#

Yeah, 99.9% AI and the rest is us helping you

shrewd apex
#

ah lets focus on the problem

slate swan
shrewd apex
#

hmm tru

slate swan
#

Yeah, ask your buddy GPT

shrewd apex
#

gl

slate swan
#

Don't forget to keep the same chat conversation so that it has context kek

hasty pike
#

Does asyncio.sleep() accepts float like 1.5?

slate swan
#

Keep using it

#

21/20 way to learn

shrewd apex
#

copilot >> gpt ducky_drawing

slate swan
shrewd apex
#

but u need to know what ur doing to use it

#

tbh ig thats true with any ai model

slate swan
#

Yet most people don't know what they're doing

tidal folio
#

Hi,
How do you make the type status say how many servers the bot is on?

slate swan
#

oh my god this is top level cringeness

tidal folio
slate swan
#

"mr been" KEKW

tidal folio
slate swan
#

It's Mr Bean jesus christ

#

Can't even get that right CS_kekw

dense barn
#

it it possible to put clickable links in code blocks on embeds?

slate swan
#

No

slate swan
#
https://www.a.com
dense barn
#

sad, text looks ugly when it's not inside code blocks

#

thankss

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

I've been trying to print an error line when an error occurs, but i can't do that using on_command_error, does anyone have any tips?

shrewd apex
slate swan
#

Why can't you do it with that event

shrewd apex
#

there is an on_error for generic ones outside of slash command and normal command scopes

#

views have on_error too

jaunty hazel
#

Is there a way to turn a reddit link into a mp4 or gif link so then when a bot pulls from a subreddit, it sends a actual playable video?

slate swan
#

example?

jaunty hazel
#

I'm currently using PRAW to pull posts at random from subreddits, see current code below:

subreddit = reddit.subreddit("- - -")
    all_subs = []

    top = subreddit.top(limit = 50)

    for submission in top:
        all_subs.append(submission)

    random_sub = random.choice(all_subs)

    name = random_sub.title
    url = random_sub.url
    


    await ctx.send(url)

Images and everything work fine, but of course if a link to a video is posted it is unable to send in a playable fashion. Is there a way to make it convert backend into a GIF/MP4 that will be posted in a playable format.

slate swan
#

you can look into it

formal basin
#

why am i getting this error

sick birch
# formal basin
with open(...) as file:
  ...
  # file is closed here

file.writelines(...) # attempting to write to file here
#

Context managers (with keyword) close resources at the end of the block

#

With files, the lock on the file is dropped at the end of the block (you can't read or write to it again)

hasty pike
#

What's new

swift edge
#

made a cog but im getting something in the terminal

slate swan
#

its awaitable

swift edge
#

RuntimeWarning anc BotBase.add_cog was never awaited

slate swan
#

BotBase.add_cog was never awaited

swift edge
#

heres the code if u want it

slate swan
#

no i dont need the code i already told you whats wrong

swift edge
#

ok

slate swan
#

the error message already tells you

swift edge
#

ohh yeah

#

im forgetting coroutine

slate swan
#

did you solve it?

hasty pike
#

await

#

Is all you need

#

Read errors
Try to understand
Figure out solution

hazy spear
#

PS C:\Users\Melih\Desktop\dearningbyloing> py main.py
Traceback (most recent call last):
File "C:\Users\Melih\Desktop\dearningbyloing\main.py", line 4, in <module>
bot.run_discord_bot()
^^^^^^^^^^^^^^^^^^^
AttributeError: module 'bot' has no attribute 'run_discord_bot'
PS C:\Users\Melih\Desktop\dearningbyloing>

#

why do i get this error

#

`import bot

if name == 'main':
bot.run_discord_bot()`

buoyant quail
#

Because your bot module doesn't have such function ยฏ_(ใƒ„)_/ยฏ

hazy spear
#

im pretty new to this so i really didnt understand you lmao

buoyant quail
#

You coded it somehow

hazy spear
#

im watching this guy on youtube and i just followed his steps and tried to run it

buoyant quail
#

You should understand what you doing

hazy spear
#

im trying to

#

just following his steps

buoyant quail
#

You missed some step then

#

Or his code is incorrect too pithink

swift edge
#

Traceback (most recent call last):
File "c:\Users\no\OneDrive\Desktop\BotStarter\main.py", line 18, in <module>
asyncio.run(main())
File "C:\Users\no\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\no\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\no\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "c:\Users\no\OneDrive\Desktop\BotStarter\main.py", line 15, in main
await load()
File "c:\Users\no\OneDrive\Desktop\BotStarter\main.py", line 10, in load
for filename in os.listdir(".\cogs"):
^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [WinError 3] The system cannot find the path specified: '.\cogs'

#

pasting is silly of me

#

thats the code

#

ive looked at the error but it doesnt show the error properly

#

if yk what i mean

buoyant quail
#

You have cogs folder?

swift edge
#

should i try doing C:\Users\BotStarter\cogs.py

swift edge
#

got a new error

#

discord.ext.commands.errors.NoEntryPointError: Extension 'cogs.cog' has no 'setup' function.

#

wait hold on

buoyant quail
#

If it's inside the command - sure

#

But why the f* you have if True lol?

swift edge
#

Guys is it possible to make your bot online 24/7

#

If it is, what should i use?

hasty pike
swift edge
#

yes

hasty pike
#

Good then

#

Host it

tight coral
#

Hey I'm looking for bot devs if anyone is interested. Message me for more information

upper inlet
#

Does anyone know the function that allows for the command to pop up in chat? I can get it to search but it doesnt show up like a bot command for viewers to see (it works just not the way I want it)

#

^the answer is Slash Commands. I got it! Thanks.

trail hare
#

How do you respond to a interaction a second time?

torn sail
#

!d discord.Interaction.followup

unkempt canyonBOT
trail hare
#

discord.app_commands.errors.CommandInvokeError: Command 'lookup' raised an exception: TypeError: 'Webhook' object is not callable

naive briar
#

That's because that's not how you use webhooks

#

You don't call the discord.Webhook object, you call its methods

#

!d discord.Webhook.send

unkempt canyonBOT
#
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message using the webhook.

The content must be a type that can convert to a string through `str(content)`.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object.

If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects to send.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
sonic vapor
#

Someone sending me their server link from this server

#

Where to report

silk wasp
sonic vapor
silk wasp
#

just dm the bot

sonic vapor
#

Ok

winter token
#
    @commands.command()
    @commands.cooldown(1, 1, commands.BucketType.user)
    @commands.has_permissions(manage_channels = True)
    @commands.bot_has_permissions(manage_channels = True)
    async def unlock(self, ctx, channel: discord.TextChannel, *, reason = None):
        guild = ctx.guild
        everyone_role = guild.default_role
        if :
            await ctx.send("The channel is not locked.")
        else:
            await channel.set_permissions(everyone_role, send_messages = True)
            await ctx.send("Done")
#

what should i add in if to make this work

slate swan
#

if True will make it work

winter token
slate swan
#

See, that's a better explanation

slate swan
#

!d discord.TextChannel.permissions_for/overwrites_for

unkempt canyonBOT
#

permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role").

This function takes into consideration the following cases...
silk wasp
#
@commands.command()
@commands.cooldown(1, 1, commands.BucketType.user)
@commands.has_permissions(manage_channels=True)
@commands.bot_has_permissions(manage_channels=True)
async def unlock(self, ctx, channel: discord.TextChannel, *, reason=None):
    guild = ctx.guild
    everyone_role = guild.default_role
    if channel.overwrites_for(everyone_role).send_messages is True:
        await ctx.send("The channel is not locked.")
    else:
        await channel.set_permissions(everyone_role, send_messages=True)
        await ctx.send("Done")


#

@winter token

slate swan
#

Then you pass the role and check the permissions

slate swan
winter token
#

!d discord.TextChannel

unkempt canyonBOT
#

class discord.TextChannel```
Represents a Discord guild text channel.

x == y Checks if two channels are equal.

x != y Checks if two channels are not equal.

hash(x) Returns the channelโ€™s hash.

str(x) Returns the channelโ€™s name.
warped mauve
winter token
#

if i await then it returns another error

naive briar
#

Send another error then

cyan ermine
#

what does this mean?

naive briar
#

It means exactly what it says

#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

cyan ermine
winter token
#
class TimeConverter:
    
    def converter(self):
        duration = None
        total = 0
        duration_pattern = r"(/d+)([dhms])"
        duration_values = re.findall(duration_pattern, duration)

        for value, unit in duration_values:
            if unit == "d":
                total += duration * 86400
            elif unit == "h":
                total += duration * 3600
            elif unit == "m":
                total += duration * 60
            elif unit == "s":
                total += duration 
        return total
cyan ermine
slate swan
winter token
dry sedge
#

I have a question nobody can answer

silk wasp
dry sedge
#

because i've asked everyone

silk wasp
dry sedge
#

actually nobody can answer

silk wasp
dry sedge
#

so basically

dry sedge
#

I've been trying to connect to a dm call or a gc call for the past year and have gotten no luck. either people don't want to answer or they don't know it

silk wasp
#

using the bot?

#

to connect to dm call and gc call? or

dry sedge
#

ive used both a bot and a account nothing works

winter token
dry sedge
#

its like impossible

dry sedge
#

I just cant figure it out

#

at all

slate swan
#

All right so, bots cannot call users and cannot be used in GDMs, that's one part solved.

slate swan
#

The other part is against the terms of services of Discord and will get your account terminated/banned

dry sedge
#

broo you dont understand your like the 200th person to tell me that ๐Ÿ˜ฆ its the only thing I dont know

slate swan
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

echo lion
#

(Krypton, do you recommend I ask my question here (see channel description, "questions") or in a help thread?)

winter token
# winter token ```py class TimeConverter: def converter(self): duration = None...
class TimeConverter:
    
    def converter(self):
        duration = None
        total = 0
        duration_pattern = r"(\d+)([dhms])"
        duration_values = re.findall(duration_pattern, duration)

        for value, unit in duration_values:
            value = int(value)
            if unit == "d":
                total += value * 86400
            elif unit == "h":
                total += value * 3600
            elif unit == "m":
                total += value * 60
            elif unit == "s":
                total += value
        return total
``` updated code still wont unmute the user after given duration is over
dry sedge
#

fiiiine

slate swan
#

Then don't ask 200 times about something that is against ToS

dry sedge
#

but do you know how to do it though like dont tell me but is it even possible

slate swan
slate swan
silk wasp
winter token
silk wasp
#

can i see the whole mute command?

winter token
unique lichen
#

Hey how to make my discord bot stream videos in voice channels?

slate swan
#

You can't

proud narwhal
#

Yes

silk wasp
#

@winter token you cant do this:

member: discord.Member or id = None

#

i dont think u can do this in a function

winter token
silk wasp
#

really? huh

winter token
slate swan
#

And why not just put member: discord.Member kek

unique lichen
slate swan
#

What you're doing is so cursed

winter token
#

just the time thing wont work

winter token
silk wasp
#

.-.

winter token
#

I wanted it to accept id as well

silk wasp
#

wow total_duration = TimeConverter.converter()

u nvr put in the durationm

torn chasm
#

how can I make my discord bot open a new websocket connection in the same vc

slate swan
silk wasp
#

pass it in the duration.-.

slate swan
#

It will accept user mention, user ID, user name and probably some others

silk wasp
slate swan
winter token
#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

hash(x) Returns the memberโ€™s hash.

str(x) Returns the memberโ€™s handle (e.g. `name` or `name#discriminator`).
torn chasm
slate swan
winter token
slate swan
#

This works by checking if the string is a mention, an ID, a nickname, a username + discriminator, or just a regular username.

winter token
#

thx

silk wasp
#

eh theres alot problem of ur mute command

#

your timeconverter is correct just themute command

winter token
silk wasp
#

this should be awaited

user = self.bot.fetch_user(id)

slate swan
winter token
silk wasp
#

actually THIS : await guild.user.add_roles(mute_role)

should just use await member.add_roles(mute_role)

silk wasp
#

eh

#

ok in the discord docs it will state if it need to be awaited or not such as if it says it is a corotine command

slate swan
winter token
#

oh

slate swan
#

And usually every fetch_ needs to be awaited

winter token
#

ok

silk wasp
#

i mean i have created a fixed of your mute command but eh i dont really wanna spoon feed you as @slate swan said

slate swan
#

Good

winter token
silk wasp
#

eh

winter token
#
                    await member.add_roles(mute_role)
                    await ctx.send(embed = embed)
                    if duration == True:
                        duration = TimeConverter.converter()
                        await asyncio.sleep(duration)
                        await member.remove_roles(mute_role)
                        await ctx.send(f"{member.mention} has been unmuted succesfully.")
silk wasp
#

alot of problem in the mute command .-. i mean alot

slate swan
#

Then go over them one by one and tell them what's wrong, that way they learn more than copy pasting an entirely fixed command :)

silk wasp
#

pain ok

#

give me a sec to see the difference of your previous codes

winter token
#

okay

#

and if I use the converter as krypton said then it would be easier?

silk wasp
#

in theory yes

#

but if u dont want to change it

#

you can use this instead

#

typing.Union[discord.Member, int]

this basically just allows the function to accept both types of inputs.

#

but u need import typing

winter token
#

o

slate swan
#

It's pointless

#

Just use discord.Member as type parameter... it's made for that

silk wasp
#

i mean ya so just do the converter instead

winter token
#

alright

silk wasp
#

of both id and member

winter token
#

imma try that method after fixing current issue

#

i just wanna learn dpy fully

silk wasp
#

if id == True
change to
if isinstance(member, int)

isinstance() is a built-in python function is used to check if an object belongs to a specified class or if it is an instance of a subclass.

slate swan
#

No, that will just go away

#

You won't have an if check as that's the point of a converter, converts the argument to a discord.Member object

silk wasp
#

oh right

#

nvm scratch that

slate swan
#

So you just need to do the lower part where you await member.add_roles(...)

silk wasp
#

the code is confusing me ,...-.

slate swan
#

typehint the arg as a Member, if it's not a member then a MemberNotFound exception will be raised ๐Ÿฆ†

#

Then always using fetch_ is not really good but you can keep that aside at the moment

#

Then your TimeConverter class won't know where duration comes from out of no where

#

You'll have to pass it as argument

winter token
slate swan
#

You should use it when you need it

#

Considering it always makes an API call, you should only use it when the cache doesn't have it

#

E.g. to get a user by ID you'd do

user = bot.get_user(ID) or await bot.fetch_user(ID)

so that you first use get_ to get from cache, and if it returns None aka not in cache, you'll use fetch_ and make an API call

#

Make some sort of get_or_fetch function if you need to return an object from it's ID

silk wasp
#

krypton i pass this to u yes?

#

im helping another person

slate swan
unique lichen
#

Just wondering , can discord bots become owner of servers

winter token
slate swan
#

yup

winter token
slate swan
#

?

winter token
# slate swan ?
def converter(self, duration):
        total = 0
        duration_pattern = r"(\d+)([dhms])"
        duration_values = re.findall(duration_pattern, duration)

        for value, unit in duration_values:
            value = int(value)
            if unit == "d":
                total += value * 86400
            elif unit == "h":
                total += value * 3600
            elif unit == "m":
                total += value * 60
            elif unit == "s":
                total += value
        return total
slate swan
unique lichen
slate swan
winter token
slate swan
unique lichen
#

Does discord.py still count it in guilds list? or like what

slate swan
#

So need to make a class etc.

#

Create a converter function that will be used as type hint

unique lichen
slate swan
buoyant quail
formal basin
#
if message.author.id == client.user.id:
        return 
   
   author_id = message.author.id
   
   curr_time = datetime.datetime.now().timestamp() * 1000

    
   if not author_msg_times.get(author_id, False):
        author_msg_times[author_id] = []

    # Append the time of this message to the users list of message times
   author_msg_times[author_id].append(curr_time)

    # Find the beginning of our time window.
   expr_time = curr_time - time_window_milliseconds

    # Find message times which occurred before the start of our window
   expired_msgs = [
        msg_time for msg_time in author_msg_times[author_id]
        if msg_time < expr_time
    ]

    # Remove all the expired messages times from our list
   for msg_time in expired_msgs:
        author_msg_times[author_id].remove(msg_time)
    
   if len(author_msg_times[author_id]) > max_msg_per_window:
     try:
        minutes = r.get(f"1 {str(message.guild.id)}")
        min = int(minutes.decode("utf-8"))
        if f'1 {message.guild.id}' not in r:
            pass
        else:
            
            duration = datetime.timedelta(minutes=min)
            await message.author.timeout(duration)
            embed = discord.Embed(title="User muted", description=f" {message.author.mention} has been muted", color=discord.Color.blue())
            embed.add_field(name = "Reason",value = "spamming")
            embed.add_field(name = "Mute duration",value = f"{min} minutes")
            for i in range(1):
             await message.channel.send(f"{message.author.mention} no spamming allowed")
             log = r.get(f"log {str(message.guild.id)}")
             log2 = int(log.decode("utf-8"))
             logging_channel = client.get_channel(log2) or await client.fetch_channel(log2)
             await logging_channel.send(embed=embed)
     except KeyError:
       pass
  ```so my bot is spamming the message.channel.send so I did for i in range(1): but still spamming it
#

how do I fix

winter token
slate swan
#

Error says all

slate swan
#

It expected a string but you gave an int to whatever function

#

just git rid of it?

formal basin
slate swan
formal basin
slate swan
#

hmm idk

#

when in need help ask chat gpt

#
if len(author_msg_times[author_id]) > max_msg_per_window:
    try:
        minutes = r.get(f"1 {str(message.guild.id)}")
        min = int(minutes.decode("utf-8"))
        if f'1 {message.guild.id}' not in r:
            pass
        else:
            duration = datetime.timedelta(minutes=min)
            await message.author.timeout(duration)

            # Check if the user has already been muted to avoid sending duplicate messages
            if not any(role.name == 'Muted' for role in message.author.roles):
                embed = discord.Embed(title="User muted", description=f"{message.author.mention} has been muted", color=discord.Color.blue())
                embed.add_field(name="Reason", value="spamming")
                embed.add_field(name="Mute duration", value=f"{min} minutes")
                await message.channel.send(f"{message.author.mention} no spamming allowed")
                
                log = r.get(f"log {str(message.guild.id)}")
                log2 = int(log.decode("utf-8"))
                logging_channel = client.get_channel(log2) or await client.fetch_channel(log2)
                await logging_channel.send(embed=embed)
    except KeyError:
        pass
slate swan
#

thats what they suggested coolidk

slate swan
silk wasp
winter token
silk wasp
#

.-.

slate swan
#

bruh

silk wasp
#

there u go

winter token
#
                    await member.add_roles(mute_role)
                    await ctx.send(embed = embed)
                    if duration == True:
                        tduration = converter(duration)
                        await asyncio.sleep(tduration)
                        await member.remove_roles(mute_role)
                        await ctx.send(f"{member.mention} has been unmuted succesfully.")
slate swan
#

Why do you still call a converter function

#

I told you to get rid of that entirely and use a converter as type hint

winter token
#

im usinga as typehint

formal basin
# slate swan when in need help ask chat gpt

I just asked ai look ```py
if not hasattr(message, 'bot_response'):
await message.channel.send(f"{message.author.mention} no spamming allowed")
log = r.get(f"log {str(message.guild.id)}")
log2 = int(log.decode("utf-8"))
logging_channel = client.get_channel(log2) or await client.fetch_channel(log2)
await logging_channel.send(embed=embed)

            # Set a flag to prevent the bot from sending another message
            message.bot_response = True```
formal basin
#

It gave me this

winter token
#

worked now thx

slate swan
#

does it work?

formal basin
slate swan
winter token
#

so im bit confused abt id part, can u tell me?

#

the param converter u said

slate swan
#

What part exactly?

winter token
slate swan
#

You can type hint most parameters to a discord type, e.g. member: discord.Member or role: discord.Role. discord.py has internal converters, e.g. discord.ext.commands.MemberConverter that will convert whatever you give as argument when executing the command to that specific type.
Each converter accepts different input, for the member converter you can give

  • ID
  • Mention
  • User name
  • Global name
  • Guild nickname

Then when you execute the command, for example !test 562359123086409729 or !test @krypton.ninja it will convert the member parameter to a discord.Member object directly and you can do various things with it

#

There's nothing to do more than add the type hint to the discord type and you will end up with the object type you want

#

Converters will also throw errors if a user, role, etc. is not found, so there's not much you need to do

buoyant quail
#

@formal basin spamming is not related to your code as it was already said multiple times. You are running multiple processes of the bot or something else like that.
Ran it by myself to show.

Except there is one thing - if you send the messages faster then you will mute the member, you can get 2-3 messages, yes

slate swan
#

Consider restarting your computer or looking at the task manager and kill all those bot instances running in the background

winter token
#

thanks krypton

swift edge
#

guys

#

im getting 2 argument error in this code

#
from discord.ext import commands

class Command(commands):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def ping(self, ctx): 
        await ctx.send("pong")```
#

im wondering what argument i should put in

buoyant quail
#

You should subclass cog, not just commands module

#

class Command(commands.Cog):

swift edge
#

k

#

ima try that

buoyant quail
#

Actually i wonder how that did work and added a command

slate swan
#

It didn't

swift edge
#

k it doesnt work ill just remove class bruh

slate swan
#

have you added the setup function bravemmlol

swift edge
#

no

slate swan
#

No wonder it doesn't work then

#

Look at the cog example here

formal basin
swift edge
#

k ill just use cog

#

i alr have a folder

#

with it in

#

im just making a botstarter folder for github

slate swan
#
 @discord.ui.select( 
        placeholder = "Choose a Role!",
        min_values = 1, # the minimum number of values that must be selected by the users
        max_values = None, # the maximum number of values that can be selected by the users
        options = 
    )```
How do i use loop in options parameter i want to fetch label value and description from database
formal basin
#

how can I fix that

buoyant quail
swift trench
#

does anyone think it would be bad if my bot checked every 2m to see your status and if you where offline it would remove your online role and visa versa?

silk wasp
swift trench
#

wym resources

silk wasp
#

if it is in a class yes

silk wasp
swift trench
#

oh yh

#

every 5 then?

silk wasp
swift trench
#

like 50

#

to 100

silk wasp
#

ya add a self. next to to bot.pool.acquire()

silk wasp
#

there also rate limit when using discord api

#

Global Rate Limit (per token): 50 requests per second
Global Rate Limit (per IP): 1000 requests per 10 minutes

swift trench
#

yh I was worried about that

silk wasp
#

so for me best around 30mins?

#

cos u have to take into account for other commands also

swift trench
#

30m is a lot tho because im trying to ping them at times but ig I could manually update it

#

doesnt have to be auto

silk wasp
#

i mean around 10mins to 30mins inbetween is fine i guess you need to trial and error

swift trench
#

true true

#

'label'?

#

what is label

#

@hasty pike

hasty pike
swift trench
#

send the code defining it

silk wasp
#

Please put them in a markdown in discord using `

swift trench
#

^^^

hasty pike
#
  @discord.ui.button(label="disable all", row=0, style=discord.ButtonStyle.primary)
  async def disable_all(self, interaction: discord.Interaction, button: discord.ui.Button):
    for item in self.children:
      if item.label == 'enable all' or 'disable all':
        continue
      item.style = discord.ButtonStyle.green
silk wasp
#

ok

#

problem is ur if statement

#

if item.label == 'enable all' or 'disable all':

buoyant quail
silk wasp
#

The second part of the condition disable all is treated as a separate boolean expression, which always evaluates to True because non-empty strings are truthy in Python.

#

so instead using or

buoyant quail
#

!or-gotcha

unkempt canyonBOT
#
The or-gotcha

When checking if something is equal to one thing or another, you might think that this is possible:

# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
silk wasp
#

use a list

#

if item.label in ['enable all', 'disable all']:

@hasty pike

#

now try if it work

silk wasp
#

you could first get all the commands name in a list first,

# Get the list of commands from your bot instance
commands = bot.commands

command_names = [command.name for command in commands]

then check for duplicates

from collections import Counter
duplicate_names = [name for name, count in Counter(command_names).items() if count > 1]

after that print out the duplicates

# Print the duplicate command names
if duplicate_names:
    print("Duplicate command names:")
    for name in duplicate_names:
        print(name)
else:
    print("No duplicate command names found.")
buoyant quail
#

It says the name in the error

#

indentation

#

You have members and for on different levels

#

But they shouldn't be

#

Slash commands it seems
Hmm, no. It gives CommandAlreadyRegistered

silk wasp
#

can i see the full command

winter token
#

is there any example of memberconverter

silk wasp
#

just add this in ur function:

member: discord.Member

#

can put it in discord mardown?

#

instead of screenshot

#

i mean paste ur code in discord

#

ok.-.

buoyant quail
silk wasp
#

i mean i cant help u if u dont so

#

?????

winter token
silk wasp
winter token
winter token
#

i didnt know just doing discord.Member does that all

winter token
cloud dawn
#

Imo using MemberConverter is more cleaner for people who don't know about the library.

cloud dawn
winter token
#

some weird examples in some website made me confused

#

abt it

cloud dawn
#

You wouldn't be the first.

winter token
slate swan
#
    async def select_callback(self, interaction,select,) :
        for value in select.values:
            role = interaction.guild.get_role(int(value))
            await interaction.user.add_roles(role)
        await interaction.response.send_message(f"Roles added" , ephemeral=True)

I have this an i want if user deselects any option remove that role how to do it?

formal basin
cloud dawn
winter token
cloud dawn
#

It is the same just that there was a shortcut created for some reason.

cloud dawn
#

I wish I could tell you more, the library is just weird. Hikari has a nice implementation tough.

silk wasp
cloud dawn
#

Or during adding?

cloud dawn
slate swan
# cloud dawn Or during adding?

i have self roles person can add roles and remove anytime they want

for eg person has selected role 1 and role 2 at beginning and next time he select role 1 and role 3 so remove role 2

buoyant quail
formal basin
cloud dawn
cloud dawn
swift trench
#
@client.event
async def on_message_delete(message):
  channel = client.get_channel(1123900671687675987)
  await channel.send(f"Message deleted: {message.clean}")
#

how do I just send the message deleted

cloud dawn
#

message.content

swift trench
#

ok thanks

#

havent coded in awhile lol

slate swan
#

what is that .clean

#

it does not exist

swift trench
#

idk

#

I was trynna think of it

cloud dawn
#

I think he meant clean_content

slate swan
#

there are docs you can always look into

cloud dawn
#

!d discord.Message.clean_content

unkempt canyonBOT
#

A property that returns the content in a โ€œcleaned upโ€ manner. This basically means that mentions are transformed into the way the client shows it. e.g. <#id> will transform into #name.

This will also transform @everyone and @here mentions into non-mentions.

Note

This does not affect markdown. If you want to escape or remove markdown then use utils.escape_markdown() or utils.remove_markdown() respectively, along with this function.

slate swan
#

!d discord.Message

unkempt canyonBOT
#

class discord.Message```
Represents a message from Discord.

x == y Checks if two messages are equal.

x != y Checks if two messages are not equal.

hash(x) Returns the messageโ€™s hash.
slate swan
formal basin
cloud dawn
#

TBH you should never use clean_content you should always dissalow your bot to mention here or everyone.

formal basin
cloud dawn
#

Feed me pls'

swift trench
#

whats the embed color format

#

I looked up html color codes

#

but thats not it right?

formal basin
swift trench
#

oh yh right

#

its all coming back

formal basin
#

or just blue, red, green, yellow

#

grey

#

i think

swift trench
#

FF0000?

#

embed=discord.Embed(title="Tile", description="Desc", color=FF0000)

formal basin
slate swan
#

no

slate swan
#

its not valid hex

swift trench
#

ff0000

slate swan
#

yes but its not proper syntax in python

swift trench
#

hm

slate swan
#

!e print(ff0000)

unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     print(ff0000)
004 |           ^^^^^^
005 | NameError: name 'ff0000' is not defined
swift trench
#

!hex

slate swan
#

!e print(0xff0000)

swift trench
#

!syntax hex

unkempt canyonBOT
#

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

16711680
swift trench
#

ohhh

slate swan
shrewd apex
#

0xffffff

cloud dawn
#

0xFF0000 == 0xF00

swift trench
#

I thought it was dat

shrewd apex
shrewd apex
swift trench
#
  embed.add_field(name=f"Category: <#{message.category.id}>", value='')
#
Traceback (most recent call last):
  File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 29, in on_message_delete
    embed.add_field(name=f"Category: <#{message.category.id}>", value='')
AttributeError: 'Message' object has no attribute 'category
cloud dawn
#

A channel has a category not a message, a message has a channel.

swift trench
#

message.channel.category

cloud dawn
#

Yep

slate swan
#

!d discord.CategoryChannel.mention

unkempt canyonBOT
slate swan
#

also mention strings properties exist

#

you can use them instead of this <#{message.category.id}>

cloud dawn
#

Oh and quick tip, be consistant with your code, use either " or '

swift trench
#

how much of an issue is that^?

slate swan
#

you are inconsistant thats the issue

cloud dawn
swift trench
#

oh word

#

thanks

#

how do I see who deleted the message?

#

I swear I have it on the tip of my tounge but

#

cant spit it out

#

got it nvm

#
  embed.add_field(name=f"Category: {message.channel.category.mention}", value='', inline='True')
#

doesnt mention the category?

cloud dawn
#

@swift trench You seem to know Python, why don't you just use the docs?

swift trench
#

oh wait can you even do that ๐Ÿ’€

swift trench
#

ive tried so many times to

cloud dawn
cloud dawn
swift trench
#

ok

cloud dawn
#
Conclusion
Itโ€™s currently not possible to mention a Discord category.
#

All you need

slate swan
swift pumice
swift trench
#

true

#
  File "main.py", line 24
    channel = client.get_channel(1123900671687675987)
                                                     ^
IndentationError: unindent does not match any outer indentation level
#

I dont understand this tho

#
@client.event
async def on_message_delete(message):
    async for entry in message.guild.audit_logs(limit=1,action=discord.AuditLogAction.message_delete):
      deleter = entry.user
  channel = client.get_channel(1123900671687675987)
#

nvm just had to look at it from this

slate swan
swift pumice
swift trench
#

can you add time in embed fields

slate swan
#

time?

#

timestamp?

swift trench
#

timestamps

slate swan
#

yes you can

swift trench
#

word

dense barn
#

is this possible to do with inline fields?

swift trench
#
  timestamp = datetime.datetime.utcnow()
  embed.add_field(name=f"Time: {timestamp}", value='', inline='True')
dense barn
#

i know you can \n your way on the first column but maybe there's a more elegant way of doing it

slate swan
swift trench
#

scrolled through and read it still have no idea what i just looked at ๐Ÿ’€

slate swan
#

!d discord.utils.format_dt

unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
winter token
#

hey, are there the examples of timedelta in py docs official

slate swan
#

!d datetime.timedelta

unkempt canyonBOT
#

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.

Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
winter token
slate swan
#

!d discord.Member.timeout

unkempt canyonBOT
#

await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").

You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
winter token
#

do i need to make converters manually or the bot will do it automatically if i use timedelta

slate swan
#

you create timedelta with 1 hour 1 minute and 10 seconds

#

and pass it to timeout

winter token
slate swan
#

if you want the user to provide time in format like 1h then yes timedelta wont understand what 1h is

winter token
slate swan
#

you can create custom converter

#

to convert it for you

winter token
slate swan
#

this is what @unkempt canyon uses

swift trench
#

im still having trouble with the time

slate swan
swift trench
#

well I dont understand how it work

slate swan
#

how what works

swift trench
#

I read everything you sent and tried like 10 different things and nothing worked

slate swan
#

so what did you try

swift trench
#
  timestamp = datetime.timedelta()
  embed.add_field(name=f"Time: {timestamp}", value='', inline='True')

I have this rn but it just returns 0:00:00

slate swan
#

yeah cause you are using timedelta

#

not datetime.datetime

swift trench
#

I tried that also

slate swan
#

and you are still just printing it not using discord syntax or helper function to convert it to special syntax

#

!d discord.utils.format_dt

unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
swift trench
#

I got this now

slate swan
#

and what is your code?

swift trench
#

well I was looking it up and I clicked the first link and there was a class for eastern time

#

so I looked at it

#

('%H:%M:%S'))

slate swan
#

its not about how you get datetime

#

its how you use it

#
  1. get datetime.datetime object
  2. pass it to format_dt function
  3. save output of the function and send it
#

go with this step list

swift trench
#

ok thanks

buoyant crescent
#

hi i still got an issue, that my commands / event in my cogs are running twice.

#

this is my main.py```python
import discord
from discord.ext import commands
import os

from apikeys import *

class MyBot(commands.Bot):
def init(self):
super().init(command_prefix= '!',intents=discord.Intents.all())

async def setup_hook(self):
    await load()

bot = MyBot()

intents = discord.Intents.default()

intents.members = True

async def load():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
cog_name = filename[:-3]
await bot.load_extension(f"cogs.{cog_name}")
print(f'Extension: {cog_name} succesfully loaded')

@bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.do_not_disturb, activity=discord.Streaming(name="Pokemon Unite", url="https://www.twitch.tv/mysterymom__"))
print("The bot is now ready")
print("--------------------")

@bot.command()
async def test(ctx):
await ctx.send("This is a text command")

initial_extensions = []

bot.run((BOTTOKEN))

slate swan
#

You probably have the bot running twice

buoyant crescent
#

this is one of my cogs ```python
import discord
from discord.ext import commands

class Greetings(commands.Cog):
def init(self, bot):
self.bot = bot

@commands.command()
async def aide(self, ctx):
    help = discord.Embed(title="Liste des commandes :", url=None, description=None, color=0x7434EB)
    help.set_author( name="Menu Help du bot", url=None, icon_url="https://cdn.discordapp.com/attachments/1122145321535930499/1122145393032040519/20230624_142400_0000.png")
    help.add_field(name="Musiques :", value="!join | !play | !stop | !resume | !pause | !music", inline=False)
    help.add_field(name="Modรฉration :", value="!ban | !kick", inline=False)
    help.set_image(url="https://media.discordapp.net/attachments/1120608535672270939/1123258060983509124/pu.gif?width=747&height=312")
    help.set_footer(text="Demandรฉ par : {}".format(ctx.author.display_name))
    await ctx.send(embed=help)


@commands.command()
async def music(self, ctx):
    await ctx.send("La liste des musiques : black_clover, black_rover, demon_slayer_3, night_dancer")


@commands.Cog.listener()
async def on_member_join(self, member):
    channel = self.bot.get_channel(1121386561150386276)
    join = discord.Embed(title="Bienvenue dans le serveur de la Neo Destiny ! ", url=None, description=f":tada: Bienvenue {member} :tada:", color=0x7434EB)
    join.set_image(url=member.avatar.url)
    join.set_footer(text=f"Nous sommes dรฉsormais : {member.guild.member_count}")
    await channel.send(embed=join)

async def setup(bot):
await bot.add_cog(Greetings(bot))```

slate swan
#

First things first DON'T change anything in he on_ready function
Its supposed to be a function called when the bot loads and in this case you shouldn't try to change the status or anything Just put there a plain
print statement.

Adding extra things in it can cause chaos .
try deleting all that in the on_ready() and mb pu thtere just print("Bot loaded").
if it all fails then idk where tf the problem is

silk wasp
sharp whale
#

Code:py class suggest(ui.Modal, title="Suggestions"): type = ui.InputText(label="Type of suggestion") suggestionbox = ui.InputText(label="Enter Your Suggestion", type =TextStyle.long) async def on_submit(self, interaction: discord.Interaction): await interaction.response.send_message(f'Thanks for your response, {self.name}!', ephemeral=True) async def on_submit(self, interaction): await suggestion_channel.send(f"The type is {self.type}")

#

Error:Traceback (most recent call last): File "main.py", line 20, in <module> class suggest(ui.Modal, title="Suggestions"): File "main.py", line 22, in suggest suggestionbox = ui.InputText(label="Enter Your Suggestion", type =TextStyle.long) NameError: name 'TextStyle' is not defined

#

@hasty pike help pls

buoyant crescent
silk wasp
slate swan
buoyant crescent
sharp whale
buoyant crescent
#

ok

buoyant crescent
hasty pike
sharp whale
silk wasp
#

.-.

hasty pike
#

What are you exactly trying

sharp whale
hasty pike
#

Well

#

Complicated one I'm bit busy RN

sharp whale
#

oky

hasty pike
#

I'll get back to you in a while

sharp whale
#

oky

silk wasp
#

wait give me a sec im checking ur cogs