#discord-bots

1 messages · Page 309 of 1

quick brook
#

Auto sync in on_connect (I'm not joking I actually looked that up)

#

The Pycord devs banned me from their server just bc they didn't include interaction checks on their Pycord support bot 😂

slate swan
#

pycord moment

slate swan
#

just send what you tried and error that you get now and someone will help

deep dome
#

how to start a thread with button interaction?

#

I have used this code and didn't work so i guess it is the wrong way

 async  def finalize_button_callback(interaction: discord.Interaction):
    await interaction.channel.create_thread(name="New thread", message="Hello Thread")
slate swan
#

!d discord.ForumChannel.create_thread

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

Creates a thread in this forum.

This thread is a public thread with the initial message given. Currently in order to start a thread in this forum, the user needs [`send_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.send_messages).

You must send at least one of `content`, `embed`, `embeds`, `file`, `files`, or `view` to create a thread in a forum, since forum channels must have a starter message.
slate swan
#

you are most likely looking for content

deep dome
#

i want to start a channel thread not fourm theard

#

the documentation shows it takes message param

slate swan
#

ah okay this kind of thread

#

well then are you getting any errors if it doesnt work

deep dome
#

interaction failed unfortunately

slate swan
#

in code error ..

deep dome
#

no it didn't show any errors

slate swan
#

are you having any error handlers

deep dome
#

Thats's a good question

#

no 😂

slate swan
#

can you show the code

final iron
#

Discord will show that if you don’t respond to an interaction within 3 seconds

deep dome
#

sorry but i have crashed my device

#

one sec

#
class StartThread():
def __init__(self, client):
    self.client = client

  @app_commands.command(name="start_thread")
  async def start_thread(self, interaction: discord.Interaction):
      embed = discord.Embed(title="Thread creation", description="Press Button                    to start thread")
    
    async  def finalize_button_callback(interaction: discord.Interaction):
          await interaction.channel.create_thread(name="New thread",                                                                message="Hello Thread")
    finalize_button =   Button(style=discord.ButtonStyle.green,label="Finalize")
    finalize_button.callback = finalize_button_callback
    view = View()
    view.add_item(finalize_button)
    await interaction.response.send_message(embed=embed, view=view)
slate swan
#

Your indentation is wrong

#

Pretty much everywhere

deep dome
#

In here only bro 😂

#

i have never used this code block right

glad cradle
fast musk
#

Whats the error you are facing?

#

btw, this is a bit of a weird way to approach it. Common way is to actually subclass view, and use the decorators to add the button and register the callback

deep dome
fast musk
#

Then you likely have an error handler that is swallowing it

glad cradle
#

that's why discord shows that error message to the user

deep dome
#

yeah when adding await interaction.response.send_message("message") it sent the message but didn't create the thread

glad cradle
deep dome
#

it worked thank you

void whale
#

were do i download the python coding for making dicord bots?

shadow acorn
shadow acorn
#

I literally said that

#

There are two options

quick brook
#

Python.org since the Ms store one breaks and doesn't work

shadow acorn
#

Sure.

quick brook
# void whale were do i download the python coding for making dicord bots?

And just to get you started

  1. Before even attempting to create a discord bot, please learn python (?tag lp)
  2. To install discord.py, please run python3 -m pip install discord.py (linux), or py -3 -m pip install discord.py (windows)
    If you wish to use voice functionality, please use discord.py[voice] instead of discord.py
  3. Take a look at https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py Mess around.
  4. When you start making your bot, use the commands ext: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html
    or if you wanna use slash commands: https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
  5. The library documentation is available at https://discordpy.readthedocs.org/en/latest/

If you need help please make a post in our #985299059441025044 Forum if its related to Python and/or Discord.py

If you are migrating from the old version of this library (1.7.x) to version 2.X.X please follow the migrating guide https://discordpy.readthedocs.io/en/latest/migrating.html

shadow acorn
#

Someone has a complex, yikes.

quick brook
quick brook
#

Chances are the C headers are not bundled

#

So you can't do #include <Python.h>

shadow acorn
#

Finished? My point has been more than proven.

grim echo
#

does anyone know how to filter out chracters from a message before it is sent

sick birch
#

Or is that from somewhere outside of discord?

grim echo
potent light
ripe sandal
#

I have hand on experience in tts and stt.

grim echo
grim echo
ripe sandal
#

got it.
you can replace the special characters of result sentence to "".

#

understand?

grim echo
quick brook
#

!d discord.Message.clean_content

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

quick brook
#

Gonna have to learn Regex to do that

grim echo
#

hmm..

jaunty wren
#

im having an issue with trying to read the custom status of a user

#

my current command is !activity_task @jaunty wren

#
@bot.command()
async def activity_task(ctx, member: discord.Member):
        print(member.activities)
        if member.activities == ():
            print("No Activity Found")
        else:
            for activity in member.activities:
                if isinstance(activity, discord.CustomActivity): 
                    print(activity)```
grim echo
jaunty wren
#

sentence = sentence.replace("#6972395", "")

#

u can do this

grim echo
#

ill give it a try

#

@jaunty wren nope

jaunty wren
#
       sentence = "i like grapes"
       keywords = ['#', '$', '%', '&']

        for keyword in keywords:
            if keyword in sentence:
                sentence = sentence.replace(keyword, "")
potent light
# grim echo is there a better way to do this?

Yeah, if it's multiple you can do something like:

import re

msg = "#123#!231$#"
new_msg, n = re.subn('[#$!]', '', msg) ##add what characters you need to change here. new_msg is the str and n is the number of character changed which you don't need in this case but you have to include it because subn returns an array.
print(new_msg)```
results: `'123231'`
grim echo
#

ill give it a try

potent light
jaunty wren
#

yes true

grim echo
jaunty wren
potent light
potent light
jaunty wren
jaunty wren
potent light
jaunty wren
#

nope

#

can i dm?

potent light
#

yeah

quick brook
grim echo
quick brook
#

there is a util to clean it out so pings are not effective

grim echo
quick brook
#

pretty sure Message.clean_content does it

grim echo
grim echo
shrewd apex
bitter knoll
#

How can I add akinator in my bot

quick brook
# bitter knoll How can I add akinator in my bot
  1. Know how it works. Do some research on how that game works, and prototype an simple python game or hell even play with some friends
  2. Once you have your prototype and plans, implement it, and test it to make sure it works
  3. Ask questions or for help on the discord.py server or in #1035199133436354600 if you are stuck on parts or if you want to clarify parts that you are unsure of

My biggest tip is with prototyping, your best friend are quite literally a piece of paper and a writing instrument. In fact, whenever I'm designing features, I always jot my ideas down on somewhere (Case and point, just like the current feature that i'm working on). A game like Akinator are just simple steps for the game loop, and rules that you have to take account in. I would highly recommend not to directly copy the feature, but base it off. Play around with it and add your own quirks to it that make it unique compared to others

#

If you need help on implementing the discord portion, hop on to the discord.py server and ask questions and folks will be able to help you (I have provided a link if you need it)

shrewd apex
unkempt canyonBOT
shrewd apex
#

make sure to use the asynchronous version

quick brook
#

that package essentially a web scraper so if you wanted to, you could use it

#

I would personally do it from scratch

shrewd apex
quick brook
#

good chance to pick up data structures and algorithms

shrewd apex
#

fair

chrome tartan
#

hi does anyone know how to configure google custom search engine and api? I'm having troubles with my image bot. Anything I ask it to display returns with"No image found"

shrewd apex
#

you would have to get more specific than that with what trouble or error u are encountering exactly

chrome tartan
#

import discord
from discord.ext import commands
import os
from googleapiclient.discovery import build
import random

intents = discord.Intents.default()
intents.typing = True
intents.presences = True
bot = commands.Bot(command_prefix="!", intents=intents, help_command=None)

api_key = ""

@bot.event
async def on_ready():
print("!!! Bot Is Online !!!\n")
@bot.command(aliases=["show"])
async def showpic(ctx, *, search):
ran = random.randint(0, 9)
resource = build("customsearch", "v1", developerKey=api_key).cse()

try:
    result = resource.list(
        q=f"{search}", cx="", searchType="image").execute()

Check if there are any items in the result
if "items" in result:
url = result["items"][ran]["link"]
embed1 = discord.Embed(title=f"Here's Your Image ({search.title()})")
embed1.set_image(url=url)
await ctx.send(embed=embed1)
else:
await ctx.send("No matching images found.")
except KeyError:
await ctx.send("An error occurred while fetching images.")

try:
bot.run("")
except Exception as e:
print(f"An error occurred: {e}")

unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

chrome tartan
shrewd apex
quick brook
chrome tartan
#

i ran a test program and yes my api key is valid

vale wing
turbid condor
frosty cliff
#

yo do u remember me

chrome tartan
turbid condor
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.

vale wing
#

Actually it's because messages containing bot's mention have content available regardless of mc intent

vale wing
shrewd apex
#

altho tbh google apis are sometimes a pain to work with

turbid condor
slate swan
#

dang haven’t been here long time

cold sonnet
#

why learn print when discord bot

cold oyster
#
@client.command()
@commands.has_role(1156220704602194012)
async def dm(ctx, member: disnake.Member, text=None):
    reciver = member
    embed = disnake.Embed(title="Message", description=f"You have recived a message from <@{ctx.author.id}>.")
    embed.add_field(name="Message below", value=text)
    await reciver.send(embed=embed)```

So I made this command, It works and all but the text in my dm is only the first word nothing else. Please help
cold oyster
cold oyster
#

I just had to be like

async def dm(ctx, member: disnake.Member, *,text=None):```
cold sonnet
#

man hit you with the thinking

cold oyster
naive briar
unkempt canyonBOT
#

discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is logged to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.

The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info).

Note

`on_error` will only be dispatched to [`Client.event()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.event).

It will not be received by [`Client.wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for), or, if used, [Bots](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#ext-commands-api-bot) listeners such as [`listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen) or [`listener()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.listener).

Changed in version 2.0: The traceback is now logged rather than printed.
sage otter
hasty pike
#

Is there something like button_clicked event?

slate swan
#

no

hasty pike
rotund creek
#

Does anyone here make money by making discord bots?

hasty pike
#

Premium subscription for bots?

rotund creek
#

Services.

hasty pike
#

So far I've paid for hosting but never earned a penny

rotund creek
#

Oh I don't think you got what I meant, what I really wanted to say is if anyone freelanced their bot making services to make money from here.

hasty pike
#

I do that 💀

#

Depends what do you mean by "here"

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

rotund creek
sage otter
#

anything that you want to do when its pressed can be added in its associated callback

shrewd fjord
#

!d discord.ui.View.wait

unkempt canyonBOT
#

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

Waits until the view has finished interacting.

A view is considered finished when [`stop()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.stop) is called or it times out.
shrewd fjord
#

u can use this :3

#

good for making generic views / buttons

sage otter
#

im not sure if this is what he wants

shrewd fjord
unkempt canyonBOT
sage otter
# shrewd fjord u can use this :3

he asked earlier if that was such thing called as "button clicked" event that he can use for Bot.wait_for() so hes trying to listen to for when the button is clicked to do something with it. views already do all of that for you as far as listening for button clicks. following execution is done within the buttons callback(which the library will also call for you as well when the button is clicked)

shrewd fjord
#

hmm my bad xd

hasty pike
#

Let's just say in simple words i have 3 buttons they have alot of functions inside but only 1 function is different so i just thought maybe i could use that listener and use if custom id statement when it comes to that function

sage otter
#

the different code for that single button that’s also different from the others would still be executed in the button's callback

#

!d discord.ui.Button.callback

unkempt canyonBOT
#

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

The callback associated with this UI item.

This can be overridden by subclasses.
nova vessel
#
    @commands.Cog.listener()
    async def on_reaction_add(self, reaction:discord.Reaction, user:discord.Member|discord.User):
        
        if reaction in self.reactions.keys():
            # Add roles to user...

I am trying to make a dictionary and then have the keys be the emojis and then the lambda function be the function to get a role object, could someone remind me how to use search for a key in a dictionary and then extract the lambda function as I have forgotten... 🤦‍♂️

slate swan
#

!E ```py
reactions = {"a": lambda x: x+1, "b": lambda x: x+2}

for case in ("a", "b", "c"):
if case in reactions:
print(reactionscase)
else:
print(f"Key {case} not found")

unkempt canyonBOT
#

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

001 | 11
002 | 12
003 | Key c not found
brittle idol
#

Can i ask question about telegram bots there?

quick brook
brittle idol
#

ok thanks:(

slate swan
white citrus
#

What do i do wrong

glad cradle
#

you can't access self inside that decorator

nova vessel
#

Anyone know how I can create a dropdown menu within an embed using discord and discord.ext

slate swan
#

Not possible within an embed

#

It'll always be below and outside the embed

nova vessel
#

Okay, how'd I go about doing that then?

slate swan
white citrus
slate swan
#

if you need data from self create a custom button class

#

#bot-commands

white citrus
slate swan
white citrus
slate swan
white citrus
slate swan
white citrus
slate swan
#

thats View ?

white citrus
#

Its the same in nextcord

slate swan
#

what does it has to do with nextcord

white citrus
#

nc.ui.View and nc.ui.Button Is equal

slate swan
#

oh really how is that

unkempt canyonBOT
#

examples/views/tic_tac_toe.py line 84

self.add_item(TicTacToeButton(x, y))```
white citrus
#

Okay and how do i do it if i would like to have 2 Buttons

slate swan
#

i guess you add two buttons

slate swan
#

working on a project need some help, with a top.gg voting system will pay

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

quick brook
#

also it's not that hard to make a top.gg voting system

#

it's really easy to do so

nova vessel
#

What's the max amount of reactions that I can add to a singular message?

quick brook
#

Not interested

shell apex
#

Pretty happy with my discord transcription bot. Joins whatever server you're in when you summon it and continously outputs a transcript from openai's whisper until its stopped

sage otter
#

ah bruh. it pings you everytime it transcribes one of your messages

#

i’d surpress those ngl

slate swan
#

I'd block the bot

vale wing
#

Apparently it's 20

glad cradle
#

LMFAO

meager orchid
#

Hello, I have a quick question. How can I make excluded roles for cd? I tried to do it through GPT code, but it didn't work. Maybe you know?

vale wing
unkempt canyonBOT
#

@discord.ext.commands.dynamic_cooldown(cooldown, type)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command)

This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.cooldown) in that it takes a function that accepts a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context) and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown) or `None`. If `None` is returned then that cooldown is effectively bypassed.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType).

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown) is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) and the local error handler.

A command can only have a single cooldown.

New in version 2.0.
meager orchid
#

Oh, sorry, forgot to mention I have a disnake)

glad cradle
#

!d disnake.ext.commands.dynamic_cooldown

unkempt canyonBOT
#

@disnake.ext.commands.dynamic_cooldown(cooldown, type=BucketType.default)```
A decorator that adds a dynamic cooldown to a [`Command`](https://docs.disnake.dev/en/latest/ext/commands/api/prefix_commands.html#disnake.ext.commands.Command)

This differs from [`cooldown()`](https://docs.disnake.dev/en/latest/ext/commands/api/checks.html#disnake.ext.commands.cooldown) in that it takes a function that accepts a single parameter of type [`disnake.Message`](https://docs.disnake.dev/en/latest/api/messages.html#disnake.Message) and must return a [`Cooldown`](https://docs.disnake.dev/en/latest/ext/commands/api/checks.html#disnake.ext.commands.Cooldown) or `None`. If `None` is returned then that cooldown is effectively bypassed.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://docs.disnake.dev/en/latest/ext/commands/api/checks.html#disnake.ext.commands.BucketType).

If a cooldown is triggered, then [`CommandOnCooldown`](https://docs.disnake.dev/en/latest/ext/commands/api/exceptions.html#disnake.ext.commands.CommandOnCooldown) is triggered in [`on_command_error()`](https://docs.disnake.dev/en/latest/ext/commands/api/events.html#disnake.ext.commands.on_command_error) and the local error handler.

A command can only have a single cooldown.

New in version 2.0.
glad cradle
#

@meager orchid

loud junco
#

but what pleasure do u get from building bot with gpt 😭

meager orchid
meager orchid
turbid condor
vale wing
#

Antipleasure

loud junco
vale wing
#

I got my application denied cause of billing info

#

Idk what I put there, apparently something idiotic for 0$ purchase

loud junco
#

still have to wait tho

robust fulcrum
#

Guys is azure cloud a good service for hosting discord bot?

quick brook
#

Henzter is

#

The major issue with Azure is that it's entirely useless in the scope of a dbot unless you use services that are exclusively tied with Azure (say you need to use MSSQL for instance). This is also same for AWS and GCP. The other major issue is that you are paying huge sums of money. I had $100 free azure credits and within 3 weeks of just running my discord bot on an container instance, I already broke past that $100 free credit range. Once that free credit is over, now azure has you on the hook, and can shut down your service at any moment without notice

robust fulcrum
#

We can't use AWS too if we are student

quick brook
#

this is why I strongly recommend purchasing an server from an VPS provider. My pick is Henzter, which is where my production bot is running as of now. Good quality service, strong background checks and good provider

robust fulcrum
#

💳

quick brook
#

but... if you are a student, then look into the GH student developer pack

robust fulcrum
#

They all need a credit card tf

quick brook
#

that offers $200 free digitalocean credits for free for 1 year if you are a student

robust fulcrum
#

They dumb tbh why would a student have a credit card , lol

shell apex
quick brook
quick brook
#

i've traditionally used my debit card and it went through

quick brook
#

those are the three options you have

shell apex
quick brook
shell apex
#

Awesome thanks

quick brook
#

so just send them like a report card or your student id, and it should be fine

shell apex
#

Perfect

robust fulcrum
#

Most GitHub education features aren't used by students like digital ocean, etc

quick brook
#

use it while you can

robust fulcrum
#

Wdym by DO?

harsh orbit
#

how to get embed message

quick brook
robust fulcrum
#

Thats needs a credit card

quick brook
#

it's used for verfication purposes

slate swan
robust fulcrum
#

Idk why they need credit card even I they don't need it

#

There are multiple other methods for verification

slate swan
quick brook
slate swan
#

if you have to verify by card you can only have one account

#

cause you can have 1 card most likely

quick brook
#

as mentioned, it's to prevent mass spam attacks

robust fulcrum
#

Azure didn't ask me for credit card

harsh orbit
# slate swan embed message?

I have bot.wait_for and when the message sent it send it to me but when the message have an embed the bot tell me the message is empty

quick brook
robust fulcrum
#

Wdym by sso?

quick brook
robust fulcrum
#

Oh

harsh orbit
# slate swan code?
message = await bot.wait_for ....
await channel.send(message)

Something like this

robust fulcrum
#

Then why can't digital ocean?

quick brook
slate swan
harsh orbit
#

say error

quick brook
#

their main consumers are actually not students

harsh orbit
#

mean it cant send an empty message

slate swan
#

did you try printing it?

robust fulcrum
#

I can't sadly use any benefit of GitHub education then

harsh orbit
quick brook
#

and then after that, there is none

slate swan
#

I cant find a tut online that works

#

can someone coach me through buidling a discord bot? Big ask i know aha

#

jesus christ that was quick

quick brook
slate swan
#

but im just as confdused when i meet this

slate swan
quick brook
#
  1. Before even attempting to create a discord bot, please learn python (?tag lp)
  2. To install discord.py, please run python3 -m pip install discord.py (linux), or py -3 -m pip install discord.py (windows)
    If you wish to use voice functionality, please use discord.py[voice] instead of discord.py
  3. Take a look at https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py Mess around.
  4. When you start making your bot, use the commands ext: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html
    or if you wanna use slash commands: https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
  5. The library documentation is available at https://discordpy.readthedocs.org/en/latest/

If you need help please make a post in our #985299059441025044 Forum if its related to Python and/or Discord.py

If you are migrating from the old version of this library (1.7.x) to version 2.X.X please follow the migrating guide https://discordpy.readthedocs.io/en/latest/migrating.html

slate swan
slate swan
quick brook
slate swan
#

Enough for basics, on a scale of one to ten, 4 or 5

robust fulcrum
quick brook
robust fulcrum
#

Have you studied async programming?

slate swan
#

thanks 👍

slate swan
slate swan
#

i mean if you understand OOP and async/await syntax you'll probs be fine

#

ill get learning 🙂

#

*cries*

quick brook
# slate swan ill get learning 🙂
- Primitive data types
- Operators
- Data structures
- Importing
- Variables, namespace and scope
- String formatting
- OOP
- Control flow
- Exception handling
- Function definitions
- Classes, objects, attributes and methods
- Console usage, interpreters and environments
- Decorators

Useful to know:
- Asyncio basics
- What is blocking?
- Logging
- knowing how to read docs properly
``` for more details see <https://gist.github.com/scragly/095b5278a354d46e86f02d643fc3d64b#required-knowledge>
robust fulcrum
quick brook
slate swan
#

Thankyou all!

robust fulcrum
#

Tbh discord bot building is boring

slate swan
#

My coding expertise lies in HTML/CSS/(a bit of)JS

quick brook
slate swan
#

kms

#

keep myself safe

slate swan
#

😭

robust fulcrum
#

Ye lol

slate swan
#

if you dont have end goal in a bot development never ends

#

I just need aa basic one that has embeds tbh not epic features

robust fulcrum
shell apex
#

^^^^^^^

#

The sad truth

slate swan
shell apex
harsh orbit
# slate swan did you try printing it?
<Message id=1159428277644038204 channel=<TextChannel id=1154125126313463889 name='ticket-39-swesra' position=7 nsfw=False news=False category_id=1135214901443432618> type=<MessageType.reply: 19> author=<Member id=1156254486403235850 name='SwesRa' global_name=None bot=True nick=None guild=<Guild id=1130898038639054940 name='SwesRa Host.' shard_id=0 chunked=True member_count=7353>> flags=<MessageFlags value=0>>

thats when I printed the object but when I print the content its print empty raw

robust fulcrum
#

the blogs on Google mostly misguide people about discord bots

#

Especially hosting bot on replit

slate swan
#

oh my days

slate swan
#

every tut on google

#

said replit

robust fulcrum
#

Mine too lol

#

I did that before 1 year

slate swan
#

dont use replit for hosting a bot joeCollapse

harsh orbit
slate swan
robust fulcrum
#

I left making discord bots after that

slate swan
robust fulcrum
slate swan
#

!d discord.Message.embeds

unkempt canyonBOT
slate swan
#

me and my buddy refused 🥴

naive briar
harsh orbit
naive briar
#

And?

slate swan
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
slate swan
#

you can get whatever you want from it

robust fulcrum
slate swan
harsh orbit
slate swan
robust fulcrum
#

Thats designing:

slate swan
slate swan
#

google says its not

#

so its true

naive briar
#

I wonder why I can't create an OS using CSS

robust fulcrum
slate swan
#

stop editing inspect element!!!!

#

jokes aha

robust fulcrum
slate swan
#

blud knows inspecting elements

robust fulcrum
#

😂

harsh orbit
#

when I get it in wait_for

naive briar
#

It's just accessing attributes like any other objects

slate swan
harsh orbit
robust fulcrum
#

You can log the attributes and see?

harsh orbit
#

how to get the content from this

naive briar
#

Get an embed of the list then get something from the embed 🤷

slate swan
#

i dont know what you mean embed content but you just access attrubute on embed object

shell apex
#

lel i got copilot just so i could ask it this one question and its trolling me so i'll ask here instead. I have

    step of process
  else
    break```
In front of every step (4 steps) of this loop, and because these steps can take considerable time (or waste considerable time if we let any go after it should stop) we have to recheck the condition between each step, since the stop flag could be thrown at any point and we want the loop broken before any more statements execute
robust fulcrum
#

If you don't know then learn?

shell apex
#

thats why im asking...

robust fulcrum
naive briar
#

The last two if statements are useless

#

If the first one fails, it will break the loop before those two are executed

shell apex
#

Unfortunately the code after the first one can take a long time and the flag can change between then (and usually will) so those extra if statements save time

shell apex
#

The problem is mainly the asyncio.sleep() separating the code (the 15 seconds to give it time to record a batch of audio, and then 2 seconds to give it processing time after) that we do not want to execute if the flag changes. But if we only check the flag at the beginning of the loop all these sleeps will execute before the final stop is called and the bot leaves, making it feel unresponsive. to get around this i put a check before each step, but it seems ugly and not the best way.

robust fulcrum
#

ye i know , sorry i misunderstood,i thought you mean you don't know

#

i am really sorry for it

shell apex
#

I apologize too, i ate some breakfast and it wasnt that big of a deal lol😆. i just was a bit frustrated after trying to explain to copilot why it wasn't fixing anything by making 2 identical loops lol

shell apex
#

Im being dumb, this is fine it just shouldnt have the breaks anywhere so that the stop is still called, the sleeps just need to be skipped over if we exit early. it looked bad at first so i felt like i was doing something wrong

shell apex
#

better

serene dawn
#

guys

#

I'm trying to start my journey learning how to make discord bots, however when I go into the console and type pip install discord, it goes through and tries to download it, but then at the end get's this error.

#

here, take a look.

sage otter
#

it says your error like 4-5 different times

#
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
final iron
#

Downgrade to 3.11, you don’t need 3.12

final iron
#

People need to downgrade and wait until the lib is updated

rugged shadow
sage otter
#

because its just as he said

#

aiohttp doesnt support 3.12

final iron
#

What does your bot say

sage otter
#

probably says coroutine object at some random memory spot

#

cuz he didnt await it

final iron
#

Oh yeah

sage otter
#

or that

#

you need to disable the internal help cmd

#

set help_command to None

#

when you create your bot object

final iron
#

!d discord.ext.commands.Bot.remove_command

unkempt canyonBOT
#

remove_command(name, /)```
Remove a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command) from the internal list of commands.

This could also be used as a way to remove aliases.

Changed in version 2.0: `name` parameter is now positional-only.
final iron
#

Or

#

Pretty sure there’s a help_command arg in your Bot() constructor

sage otter
#

personally i like to set it to None on startup when you initialize your bot class

final iron
#

You can just set that to None

naive briar
#

In the bot's constructor, set help_command to None

sage otter
#

its like i dont speak english or sum when i say these things

final iron
#

No harm in clarifying things

sage otter
#

not at all.

worn violet
#

Have u made discord bots

sage otter
#

only on certain days verycool

#

did you ever even fix this

#

by awaiting the ctx.send()

#

as a tip, saying "its not working" or anything along those lines isnt a very productive phrase. generally, in help channels like this, you want to be as precise as you can.

#

if you have any errors for example, those should be posted here as well with your issue

#

fair enough

quick gust
#

💀

rugged shadow
#

then practically you didn't ask for help

burnt coral
#

seriously.. you join an online community full of enthusiastic developers eager to help others on their spare time and your response is this when you're suggested to be more pedantic and precise when asking for help? grow up.

final iron
#

You’re infinitely more likely to get help by describing the issue, than just saying it doesn’t work

#

This is explicitly listed in the help guide

white citrus
#
        self.button_one_label = nc.ui.TextInput(label="Button 1 (Blue)", style=nc.TextInputStyle.short, max_length=50, required=True, placeholder="Contact Staff")
        self.button_two_label = nc.ui.TextInput(label="Button 2 (Red)", style=nc.TextInputStyle.short, max_length=50, required=False, placeholder="Report Member")
        self.button_three_label = nc.ui.TextInput(label="Button 3 (Grey)", style=nc.TextInputStyle.short, max_length=50, required=False, placeholder="Other")

        self.add_item(self.header)
        self.add_item(self.textbox)
        self.add_item(self.button_one_label)
        self.add_item(self.button_two_label)
        self.add_item(self.button_three_label)

    async def callback(self, inter: Interaction):
        if not self.button_two_label.value and self.button_three_label.value:
            view = TicketMain_One(self.header, self.textbox, self.button_one_label)

        if self.button_two_label.value:
            if not self.button_three_label.value:
                view = TicketMain_Two(self.header, self.textbox, self.button_one_label, self.button_two_label)            
            else:
                view = TicketMain_Three(self.header, self.textbox, self.button_one_label, self.button_two_label, self.button_three_label)    

        if self.button_three_label.value:
            if not self.button_two_label.value:
                view = TicketMain_Two(self.header, self.textbox, self.button_one_label, self.button_three_label)
            else:
                view = TicketMain_Three(self.header, self.textbox, self.button_one_label, self.button_two_label, self.button_three_label)

        print(view)
        await inter.response.send_message(view=view)```
#

I dont get a View

#
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\modal.py", line 268, in _scheduled_task
    await self.callback(interaction)
  File "c:\Discord\Maja Projekt\Maja-Beta\modules\ticket_system\view.py", line 46, in callback
    print(view)
UnboundLocalError: local variable 'view' referenced before assignment
slate swan
#

meaning none of the ifs were invoked

#

!e ```py
if False:
x = 1
print(x)

unkempt canyonBOT
#

@slate swan :x: Your 3.12 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(x)
004 |           ^
005 | NameError: name 'x' is not defined
white citrus
slate swan
white citrus
eternal sparrow
#

hello everyone

#

i want to make a Welcomer command, what can i do ?

#

my code is here :

#
@client.event
async def on_join(member):
  guild = client.get_guild(1159111020040683560)
  channel = guild.get_channel(1159111020040683564)
  await channel.send(f"Hi {member.mention}, Welcome to the server!")
#

the bot is online but don't respond

#

should i make something like member = ...

#

ping me if you respond please

final iron
#

!d discord.on_guild_join

unkempt canyonBOT
#

discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild) is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) joins a guild.

This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds) to be enabled.
eternal sparrow
#
@client.event
async def on_join(member):
  discord.on_guild_join(guild)
  guild = client.get_guild(1159111020040683560)
  channel = guild.get_channel(1159111020040683564)
  await channel.send(f"Hi {member.mention}, Welcome to the server!")```
#

is the code right, now ? @final iron

final iron
#

No

#

on_join doesn’t exist, it’s not an event

#

!d discord.on_member_join

unkempt canyonBOT
#

discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).

This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled.
final iron
eternal sparrow
#

i don't understand very well

#

sorry

final iron
#

It’s pretty basic

#

Not sure what else to explain tbh

eternal sparrow
#

idk too

final iron
#

I’d read the docs and look at some examples if you’re still confused

eternal sparrow
#

i am a begginer + an idiot

final iron
#

!d discord.Client.event

unkempt canyonBOT
#

@event```
A decorator that registers an event to listen to.

You can find more info about the events on the [documentation below](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events).

The events must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine), if not, [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) is raised.

Example

```py
@client.event
async def on_ready():
    print('Ready!')
```...
final iron
#

I’d read this

eternal sparrow
#

still can't understand

#

now i have another problem

final iron
unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

harsh orbit
#

how to make that if I restarted the project of the bot the buttons still working

#

cuz it broke when I restart it

final iron
harsh orbit
#

?

#
    def __init__(self):
        super().__init__(timeout=None)
        self.Value = None

    @discord.ui.button(label=" إغلاق التذكرة 🔒.", style=discord.ButtonStyle.danger)
    async def close(self, interaction: discord.Interaction, button: discord.ui.button):

Same as my button

final iron
#

You obviously haven’t

harsh orbit
#

._.

#

how I knew that is same as my button?

final iron
#

It’s not

#

It’s not the same lmao

#

Go through and actually read the examples

harsh orbit
#

Im not finding any thing diffrent than my way
also I tried to run this code and it gives error lol

#

you can just tell me the way without this

final iron
#

They literally explain it lmfao

final iron
#

That’s what I thought lol

#

Read over it carefully

#

Your code is not the same as the example

#

You’re missing key parts that the comments in the example explain

harsh orbit
# final iron Okay sure, where’s your custom ID?
class PersistentView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label='Green', style=discord.ButtonStyle.green, custom_id='persistent_view:green')
    async def green(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('This is green.', ephemeral=True)

this button is right for you?

#

custom_id + timeout is None

final iron
harsh orbit
#

when I reset the project it broke

final iron
#

Show how you’re adding the view

harsh orbit
#

await ctx.send(view=PersistentView())

final iron
#

So for the third time, read over the example

#

This is my final time saying this

#

This is not productive. The GitHub gives you exactly what you need if you actually take 2 seconds to read it over

slate swan
#
  @commands.command(aliases=['gr','grole'])
  @commands.has_permissions(manage_roles=True)
  async def addrole(self,ctx, role: str, member: discord.Member):
    await member.add_roles(role)
    embed = discord.Embed(description = f'{emoji.check} role **{role}** has been `gave` to {member.mention}', color=color.color)
    await ctx.reply(embed=embed,mention_author=False)
#

code and my error is

#

@final iron

final iron
#

Also, you're showing the wrong command

slate swan
#

yo

final iron
#

You used watch and you're showing addrole

slate swan
#

wym

#

the role is watch

#

a aliases is gr ?

#

my name is watch

final iron
#

Oh

#

Anyway, share the traceback

#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles) to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s must appear lower in the list of roles than the highest role of the member.
final iron
#

Also add_roles takes a snowflake and you're passing in a string so that won't work

slate swan
#

oi

final iron
#

That's probably the issue

slate swan
#

imma try that rn

#

same error

#

@final iron

final iron
#

What’s the code

slate swan
#

wym like the bot?

#
  File "/home/runner/scare1/.pythonlibs/lib/python3.10/site-packages/discord/member.py", line 1051, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'str' object has no attribute 'id'

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

Traceback (most recent call last):
  File "/home/runner/scare1/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/scare1/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1029, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/scare1/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 244, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'id'
~```
final iron
slate swan
#
import discord
from discord.ext import commands
from util import color , emoji
import datetime  
from discord import app_commands
from discord.utils import get

class role(commands.Cog):
  def __init__(self, client):
    self.client = client

  @commands.command(aliases=['cr','crole'])
  @commands.has_permissions(manage_roles=True)
  async def createrole(self,ctx,*,name):
    guild = ctx.guild 
    await guild.create_role(name=name)
    embed = discord.Embed(title = f'', description = f'{emoji.check} role **{name}** has been `created`', color=color.color)
    await ctx.reply(embed=embed,mention_author=False)

  @commands.command(aliases=['gr','grole'])
  @commands.has_permissions(manage_roles=True)
  async def addrole(self,ctx, role, member: discord.Member):
    await member.add_roles(role)
    embed = discord.Embed(description = f'{emoji.check} role **{role}** has been `gave` to {member.mention}', color=color.color)
    await ctx.reply(embed=embed,mention_author=False)


async def setup(client):
  await client.add_cog(role(client))
final iron
#

Well this changes nothing

#

role is still a str

#

You could typehint it to discord.Role and see if discord.py will automatically convert it

slate swan
#

how do i make it a snowflake

#

???

#

FIXXED IT

#

W MAN THANK U!

naive briar
#

Prefix or slash commands?

#

Call the sync method of the command tree

quick brook
#

did you sync?

naive briar
#

!d discord.app_commands.CommandTree.sync

unkempt canyonBOT
#

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

Syncs the application commands to Discord.

This also runs the translator to get the translated strings necessary for feeding back into Discord.

This must be called for the application commands to show up.
quick brook
#

in a manual sync comamnd

#

just as a primer:

App commands work differently from message commands, they're handled mostly on Discord's end. Discord just tells your bot when someone successfully triggers a command.
In order to do this, you need to register your commands on the command tree then tell discord they exist by syncing with tree.sync.
Commands can be registered on the tree either as a global command or as a guild-specific command, and must be synced to the same scope they are associated with in the tree.
When you sync, you are telling Discord about the commands you currently have for a particular scope.

To sync global commands: await tree.sync()
To sync guild commands: await tree.sync(guild=guild)
Guilds must be either a Guild object or a discord.Object with the guild's id.

It may help to think of the tree as a dict like this.

{
  None: [global, commands],
  guild_one: [guild, one, commands],
  guild_two: [guild, two, commands]
}

copy_global_to will copy [global, commands] and add them to the commands for the guild you pass.
This is only done locally, you must still sync.

All commands are global by default. There are a few ways to make them guild-specific:

  • @app_commands.guilds() decorator on an app_commands.Group sublcass or @app_commands.command()
  • guild/guilds in @tree.command()
  • guild/guilds in bot.add_cog, only if the cog is a GroupCog
  • guild/guilds in tree.add_command, not typically used

A common practice for syncing is to pick a specific guild for testing and run tree.copy_global_to(guild=guild) then tree.sync(guild=guild).
When you're done testing, tree.clear_commands(guild=guild) then tree.sync(guild=guild).
When you're ready to publish your commands, tree.sync().
?tag umbras sync command makes this flow easy using !sync *, !sync ^, and !sync, respectively.

?tag sync - why you shouldn't auto-sync
?tag whensync - when you should sync
?tag umbras sync command - a prebuilt sync command

#

you should use a sync command such as this one:

Moved the massive codeblock to a blog post.

Enjoy!

#

did you read it and understand how that sync command works?

naive briar
#

That comes out as annoying

quick brook
#

then do you know how to make commands?

#

you can put it in a cog or where your commands go

naive briar
#

Where you want your commands to be synced, preferably not blind automation

quick brook
#

in your bot file...

#

i'd recommend looking at the basic examples on the gh repo in order to figure it out

naive briar
#

Put what where? pithink

quick brook
#

in a prefixed command

#

!help for example

#

the point is that you need to make a prefixed command in order to sync slash commands

naive briar
#

You can't sync in slash commands if you've never synced before

quick brook
#

Auto Syncing Sucks

#

you manually sync with a prefixed command using the command that I gave you eariler

#

The reason why auto syncing sucks is that you send unneeded API requests to discord, as slash commands are handled by discord directly. In order to get those commands to discord, you do something called syncing. And the way you do the syncing is by making a prefixed command in order to sync those, since you can't sync slash commands with a slash command for the first time

#

i answered this multiple times for you

#

you will have to swap out discord.Client for commands.Bot instead

#

commands.Bot subclasses from discord.Client, plus gives you a tree already to work with (can be accessed from commands.Bot.tree)

quick brook
naive briar
#

There's a reason why Python have if-statements

quick brook
naive briar
#

And what is it?

quick brook
naive briar
#

That's why you just need to check first

quick brook
#

if you dont do it entirely in the first place, then why need a check?

#

i fail to understand your argument here

naive briar
#

And what's the reason not to do it?

quick brook
naive briar
#

I'd just store previous app commands info in a file and check the current one against it, to see if they're different or not

quick brook
# naive briar I'd just store previous app commands info in a file and check the current one ag...

Sync when you...

  • Basic
    • Added/Removed a command
    • Added/Removed autocomplete (decorator, transformer)
    • Added/Removed an argument
    • Added/Modified/Removed locale strings
    • Converted the global/guild command to a guild/global command
  • Modify
    • Changed a command's...
      • name (name= kwarg, function name)
      • description (description= kwarg, docstring)
    • Changed an argument's...
      • name (rename decorator, param name)
      • choices (Literal, choices decorator, enum type)
      • description (describe decorator, docstring)
      • type (arg: str str is the type here)
  • Permissions

Do not sync when you...

  • Changed anything in the command/autcomplete function's body (after the async def (): part)
  • Added/Modified/Removed library side checks:
    • (@)app_commands.checks...
    • (@)commands...(.check)
    • @app_commands.checks.(dynamic_)cooldown(...)

This is the same for hybrid app commands

#

here is a list of when you need to sync

quick brook
# naive briar All that can be automated

this is the case where it's better to trade off automation with control. With umbras sync command, you gain control on how you sync, and if you screw up (say synced globally and then synced to guild, and now you have duplicate commands), that can be fixed easily with !sync ^

naive briar
#

And? I just said ...check the current one against it, to see if they're different or not, if they're different, then sync

quick brook
#

bot.command

naive briar
quick brook
quick brook
quick brook
#

correct. then you can use @bot.command

quick brook
#

are you going to store the changes on every single time you start the bot?

naive briar
#

Information of the previous - current, I just said it all

final iron
#

command_prefix is requred iirc

#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.
quick brook
naive briar
quick brook
#

you would have to do that anyways

naive briar
quick brook
#

i know what it means to auto sync

naive briar
#

How is that relevant here?

quick brook
naive briar
#

And what is wrong with conditional auto syncs?

quick brook
naive briar
#

That is just a bit more start-up time

quick brook
naive briar
#

How many commands do you have to think that difference comparison will take that long?

naive briar
#

Who will ever need that many?

quick brook
naive briar
#

That is still just more start-up time

quick brook
naive briar
#

Sure would

quick brook
#

make a bot that has 100 commands, and bring me the statical data

#

geometric mean included

naive briar
#

No one make a bot with that many commands, unless you make a command for every choice instead of using choices

quick brook
naive briar
#

How is that?

#

All I see here is just you refusing to accept a little thing

quick brook
#

you gave 0 evidence to back yourself up

naive briar
#

Evidence of?

quick brook
#

i presented it all

#

you presented none

naive briar
#

I already told you, conditional auto sync, that doesn't sync every time blindly

slate swan
#

tbh I just have an auto-sync in setup hook and quote it out if i don't need it

quick brook
#

every single time you restart your bot, even with no changes you are still sending wasteful api requests to discord

slate swan
#

which is why I called it an auto-sync confusedDumb

#

read my message properly lol

quick brook
#

you basically can't convince me unless there is evidence (and proper evidence) that conclude your thesis. statements such as conditional auto syncing are still at the very end, opinions

naive briar
#

And what kind of evidence?

quick brook
naive briar
#

You have no evidence against conditional auto syncs, just blind ones

#

That I agree

quick brook
#

you are getting there. it should be @bot.commands()

#

the ()

#

the @bot.commands doesn't have () at the end

#

ok you don't really need message starts with when working with prefixed commands. dpy handles it for you

#

in your case, the prefix is *

#

basically like that

#

what's the command looking like right now?

#

no you dont need to

final iron
#

bot.command() is a decorator

quick brook
#

after that, paste in the command found here. Adjust the code as you need:


from typing import Literal, Optional

import discord
from discord.ext import commands

@bot.command()
@commands.guild_only()
@commands.is_owner()
async def sync(ctx: commands.Context, guilds: commands.Greedy[discord.Object], spec: Optional[Literal["~", "*", "^"]] = None) -> None:
    if not guilds:
        if spec == "~":
            synced = await ctx.bot.tree.sync(guild=ctx.guild)
        elif spec == "*":
            ctx.bot.tree.copy_global_to(guild=ctx.guild)
            synced = await ctx.bot.tree.sync(guild=ctx.guild)
        elif spec == "^":
            ctx.bot.tree.clear_commands(guild=ctx.guild)
            await ctx.bot.tree.sync(guild=ctx.guild)
            synced = []
        else:
            synced = await ctx.bot.tree.sync()

        await ctx.send(
            f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
        )
        return

    ret = 0
    for guild in guilds:
        try:
            await ctx.bot.tree.sync(guild=guild)
        except discord.HTTPException:
            pass
        else:
            ret += 1

    await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")
#

dont worry about the content of the command itself

#

essentially the way you use this command is like this:

*sync - Globally sync (meaning that on every server, the command is visible and usable) to Discord

*sync ~ - Takes all of the commands that your bot has in your server, and then syncs it to that guild

*sync * - Copies the global commands and syncs it into your bot

*sync ^ - Clears out any guild commands and resyncs. This is used if you have duplicate slash commands showing up

*sync 123 - Syncs all of the commands to the given guild id. Replace 123 with the guild id that you want to sync to

#

i'd start off with *sync 123 (replace 123 with your guild id), and then wait a bit for them to show up

#

it might take some time

#

yes i've done it a ton of times

#

up to 45 seconds or so. i've not timed it so it may take longer or shorter for you

#

there isn't a set time for that

sick birch
#

<@&831776746206265384>

slate swan
#

Where did you define tree since you're not using self. prefix

#

And don't sync commands in on_ready event

#

Ah yeah and since you're using discord.Client and not discord.ext.commands.Bot - you can't use slash commands

final iron
#

!d discord.Client

unkempt canyonBOT
#

class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

async with x Asynchronously initialises the client and automatically cleans up.

New in version 2.0.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).
final iron
#

Yeah you can, you just have to create the command tree yourself

#

With Bot it’s automatically created

slate swan
#

Yeah that's why I said where tree is defined if they aren't using self.tree which is not possible on a client

fading granite
#

hi. i want to find out the total number of threads in a particular forum channel. i tried using len(forum.threads) but it only returned the open ones. there are a lot of archived threads. how do i count them too?

slate swan
#

Don't do these things in on_ready

turbid condor
#

!d discord.on_ready

unkempt canyonBOT
#

discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.guilds) and co. are filled up.

Warning

This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
turbid condor
#

Read the warning

vale wing
#

He hit da griddy

merry cliff
#

No way

slate swan
slate swan
naive briar
#

Even if there are 100 commands, it would not take more than a second

glad cradle
#

is that 2ms?

naive briar
unkempt canyonBOT
#
Available tags

» slicing
» sql-fstring
» star-imports
» str-join
» string-formatting
» strip-gotcha
» tools
» traceback
» type-hint
» under
» underscore
» venv
» virtualenv
» voice-verification
» windows-path

honest marten
#

/help

fading granite
#

does discord delete older threads in forum channels? i’m getting an incorrect count when i use .archived_threads() command

vale wing
#

How do you verify the count

robust fulcrum
#

how can we get the id of a webhook?

shrewd fjord
#

oh nvm looks like dpy to me :3

#

actually tbh i have 90+ app commands only takes less than a sec

unkempt canyonBOT
robust fulcrum
#

ty

halcyon kestrel
#

Best way to learn?

glad cradle
#

docs and examples

bitter tundra
#

Why I am getting this error, I did install the build tools?

I wanted to install py-cord

naive briar
#

Are you using Python 3.12?

bitter tundra
#

yes

naive briar
#

That's a well known issue, I believe that they're working on fixing it

night crater
#

Dont use 3.12 for a while

#

a lot of packages will take time to support it

cold oyster
#

How do I install discord_components?

#

I saw it in a github repo and idk how to install

slate swan
#

Why would you need it

cold oyster
# slate swan Why would you need it
PS C:\Users\HP\Desktop\bot> pip install discord-components          
ERROR: Could not find a version that satisfies the requirement discord-components (from versions: none)
ERROR: No matching distribution found for discord-components```

To make buttons
sage otter
#

but like

#

dpy already has that

#

you don’t need third parties anymore.

#

i honestly don’t know why people also still use forks anymore tbh

cold oyster
#

Huh?

#

@sage otter wdym

slate swan
cold oyster
slate swan
#

Again, use discord.py or whatever other library you're using

#

discord-components is deprecated and should not be used.

cold oyster
#

ohh alr

slate swan
#

and that since December 2021

shrewd fjord
#

Dpy supporting since 2021?

#

hmmm

slate swan
#

Not what I said

slate swan
slate swan
#

what perms would it be for like for inviting a bot just for it to dm ppl in a server

final iron
#

DM people in a server shipit

slate swan
#

yea its for a mod dm

#

thing custom for a server

final iron
#

You wouldn't need any of them

#

!d discord.Guild.members

unkempt canyonBOT
slate swan
#

oi it says i need them

final iron
#

No shit

#

ctx.message.delete()

#

Deleting a message is very different from what you told me

slate swan
#

oh im sorry

final iron
#

You'd need Manage Messages

slate swan
#

yeah

rough shuttle
#

Hey anyone wanna work in a joint discord bot project? (I am a beginner with enough information i think)

rough shuttle
#

😭

#

i am thinking of deciding it with my partner

turbid condor
#

welp that's the first thing you should come up with

#

and then tell your idea if anyone interested he or she will tell you

rough shuttle
#

but i clicked ur OF link, wtf that

turbid condor
rough shuttle
#

okay

turbid condor
#

tho why u want to make a discord bot?

#

like your motive to? Is it to test out your knowledge? or something else

rough shuttle
#

and maybe put it up on public for extra cash if the project goes successful

#

and also put it in my porto for future purposes

#

sorry for late replies, i had to go somewhere

turbid condor
vale wing
#

Oh heck monetisation is harder than you think

turbid condor
#

coming up with something unique is even harder

vale wing
vale wing
#

☺️

rough shuttle
#

🤨

vale wing
#

It's bobux bot

rough shuttle
#

WHAT IS BOBUX BOT

rough shuttle
#

ur bot..?

vale wing
#

I am project manager, bot is owned by team

rough shuttle
#

is there any way I can join the team?

vale wing
#

Bro why tf does it look like I am promoting bot

turbid condor
vale wing
#

I will dm you details if interested

rough shuttle
vale wing
#

Best fork

#

Except we highly altered views and modals implementation

turbid condor
#

welp i don't know but i feel comfortable with dpy

rough shuttle
#

I only know discord py 😭

#

i hope its okay, i am willing to learn

#

disnake

glad cradle
#

it's pretty much the same as d.py but better

shrewd fjord
#

i dunno why people mostly hate on their parents, talking about in python library cases not irl pendark

glad cradle
#

what 🧐

turbid condor
#

he meant that disnake is a fork of dpy in a sense calling dpy parent of disnake

#

tho in the end it depends on what you feel comfortable with

sage otter
#

no one typically hates on dpy. moreover they more so blame the developer for his past absence from development.

#

dpy isn’t bad. its certainly better than most of the forks that people made to replace it

glad cradle
glad cradle
sage otter
#

not really.

glad cradle
#

So what makes you think that

sage otter
#

a lot of how some of them did new implementations. for example novus/nextcord(i think). the interactions implementation they did is very obsolete and generally "bad". for example, dispatching internal events to listen to as far as buttons clicks and select menu selections

#

nextcord and pycord has already have both already had their fair share of bad code reviews

glad cradle
sage otter
#

why would i also need to view 90% of the code when 90% is still written by the original developer

glad cradle
#

you can't even state that since you haven't actually looked at the code

sage otter
#

they're forks. the general code base will stay relatively the same from the parent library

#

most of them weren’t made to change what danny did. moreso to add on and continue what he left

glad cradle
#

Since I only know Disnake as Fork I will only talk about that, I can assure you that Disnake has changed more than the 50% of the code base

sage otter
#

notice how i didn’t mention disnake in my initial statement as well as how i didn’t mention all of the forks but rather most of them

glad cradle
#

you said forks generally, disnake is a fork, therefore you're also talking about it

sage otter
#

i don’t really hate on disnake

#

from what i hear it’s an ok alternative to the actual library

#

however i never really got into it because i stuck with the main library for my own reasons

shrewd fjord
velvet sigil
#

anyone here to help related discord bots

naive briar
burnt coral
# glad cradle So what makes you think that

dpy has been around for a long time and has developed a significant community.. the number of contributors and the maturity of their present implementation is a no-brainer when compared to dpy forks (most of which were forked while danny was absent)

old vine
#

hey..

#

can someone help me?

naive briar
old vine
#

this might be simple but i am kinda still stuck with it

#

yk a forum post right

naive briar
#

Yes

old vine
#

i am trying to make a slash command that like locks a forum post at a certain time and unlock it at a certain time... i know how to do the lock and unlock. i am comfused on how to input the forum post like a normal text channel

naive briar
old vine
#

cuz if it was text channel, i could just do this

#

but for forum, i can't select a post

naive briar
#

I don't think you can

old vine
#

how do i do it now?

naive briar
#

You can resort to the threads' IDs or make the command lock/unlock the thread it was called in

naive briar
#

By threads, I mean the forum posts

old vine
naive briar
loud junco
#

finally got my github student dev pack
which is the best host in the bundle

#

digitalocean heroku replit so many choice =.=

turbid condor
loud junco
turbid condor
#

Heroku isn't made to deploy bots as for replit you know the case

#

Heroku is for websites

loud junco
turbid condor
#

Probably

loud junco
#

but i dont have one :D

turbid condor
#

Even a mobile wallet works if it has an e-card

#

Tho i haven't tried digital ocean

shrewd fjord
#

Well for digitalocean verification, you must add a card / paypal and pay then up wither 5$ for a just a basic use case or 12$ (maybe 10$) to use for production use case and for verifying urself

#

I like how digital ocean making you pay to only verify that you are adult xd

turbid condor
#

I'd rather got to hetzner

shrewd fjord
#

Fr

loud junco
turbid condor
#

Welp there is nothing that can help you with discord bot hosting

shrewd fjord
#

Use aws ig

loud junco
turbid condor
shrewd fjord
#

It comes pretty sure

shrewd fjord
turbid condor
#

Tbh u can use an e wallet I'm pretty sure almost everyone has a sim card

loud junco
#

and my e wallet only has 34 cent in it :D

shrewd fjord
#

Then use AWS

#

Comes 1 year credit with github student pack i think

turbid condor
#

Yeah u can probably get aws

turbid condor
shrewd fjord
#

Oh nvm

turbid condor
#

Anyone can use it

#

Same for gch

shrewd fjord
#

Mhm wasn't sure lol

rugged shadow
#

@loud junco it comes with azure

#

which you don't need a cc for

loud junco
turbid condor
#

Only 1 year trial

loud junco
#

so it has a database and 247?

turbid condor
#

It's a hosting service so yeah it's 24/7 as for database you might need to see the details I'm not sure about that

vale prairie
shrewd fjord
unkempt canyonBOT
#

class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild)...
shrewd fjord
#

!d discord.Role.members

unkempt canyonBOT
rugged shadow
shrewd fjord
#

There you go

vale prairie
#

Thank you

shrewd fjord
#

You said u have e-card or smth

halcyon kestrel
#

Is discord js better then discord py

naive briar
#

Define better

civic reef
#

I am in need of discord bot developers
we need to do some work with CodeForces API and some other work

#

is it fine then DM me

slate swan
#

Use Fiverr and similar for that

bitter knoll
#

Have any one worked with pyrogram framework

sinful surge
#

never even heard of it

bitter knoll
#

Oh

sinful surge
#

Why asking?

bitter knoll
#

I am finding someone who can help me with some things

turbid condor
#

!pip pyrogram

unkempt canyonBOT
#

Elegant, modern and asynchronous Telegram MTProto API framework in Python for users and bots

glad cradle
#

hi there, has someone here ever messed with adding a user to a dm group? (yes it's an oauth2 endpoint)

coz i have few questions

wind radish
bitter knoll
wind radish
#

if ur smart enough in py no lol

halcyon kestrel
glad cradle
bitter knoll
#

I think both are good on their own war

turbid condor
bitter knoll
#

Ya

turbid condor
#

So on which bases are we gonna compare them

halcyon kestrel
#

i feel like js is better

bitter knoll
turbid condor
#

And can you tell how it's more stable

#

And what is the thing in discord.js that you can't do in py

turbid condor
#

Or in term of ppl

shrewd fjord
#

Wont get suitable answers here

turbid condor
#

Wait nvm not ppl they look the same

turbid condor
shrewd fjord
#

Why would it start?

naive briar
#

I don't know why you would even learn Js if it's not for web dev

shrewd fjord
#

Node.js

sick birch
glad cradle
sick birch
#

However it's eaiser to write unsafe code with JS

shrewd fjord
glad cradle
#

also the endpoint is bad documented but I'm not even surprised

shrewd fjord
#

You shouldn't be

#

Discord docs is the most shittest i have ever seen 💀 no offense

turbid condor
#

Are we still on topic of disnake and dpy?

glad cradle
#

no i and spooky are talking about the discord api

shrewd fjord
naive briar
#

And those took longer than it should to look for

glad cradle
sick birch
turbid condor
glad cradle
shrewd fjord
glad cradle
#

ig noone touch the bad documented endpoints otherwise they would've already fixed / improved them

turbid condor
#

Yeah ig they are rarely used

shrewd fjord
glad cradle
#

there are only 2 endpoints that are quite useless

shrewd fjord
#

They just released the spec so maybe will take some time

slate swan
#

If you have a question, ask it so everyone may learn from it and don't ask for DMs, it's weird as well.

raven iron
#

` import os

import discord

client = discord.Client(intents=discord.Intents.default())

@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
if message.author == client.user:
return

if message.content.startwith('$hello'):
await message.channel.send('Hello!')

client.run(os.getenv('TOKEN')) `

when running this I am given the error "expected a token to be str, received NoneType instead" what do?