#discord-bots

1 messages · Page 321 of 1

fiery girder
#

ok

#

this is when i start the command

#

when i got 2 letter correct but the letter is challange so it dont match that

#

whenever i get one wrong

#

is fixed it self @final iron

#

but not the underscores

#

oh wait

#

i think i got it fking discord

#

two underscore make it disapear

#

_ _

#

thats why it dispearing

#

i just gotta find a good subsitude for underscore

harsh orbit
shrewd fjord
#

Huh hangman

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) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#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) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
shrewd fjord
#

You make a PUT request to the api to send msg

shrewd fjord
#

____

#

With \ ^

#

Without \


brittle gyro
#

Is anyone having issues with the discord.py-self API?
I am getting the error:
ValueError: invalid literal for int() with base 10: 'ER_V2_'

shrewd fjord
#

What lib even is this?

#

!pip discord.py-self

unkempt canyonBOT
shrewd fjord
#

If its about self bot then its against discord TOS

brittle gyro
harsh orbit
#

I want to send message with discord bot when a link routed

shrewd fjord
harsh orbit
#

I want example for it

harsh orbit
shrewd fjord
harsh orbit
#

I did this and didnot work

#
import requests

payload = {
    'content': "tst"
}

header = {
    'authorization': "my bot token"
}

r = requests.put("https://discord.com/api/v10/channels/1160897083792965685/messages", data=payload, headers=header)
#

this is not working

sick birch
shrewd fjord
#

Not payload

#

You have to use the json param

#

And yeah header is wrong too

#

And instead of requests.put use requests.post

harsh orbit
#
import requests

payload = {
    'content': "tst"
}

header = {
    'Authorization': "Bot"  "bot token"
}

r = requests.post("https://discord.com/api/v10/channels/1160897083792965685/messages", json=payload, headers=header)

also this not working

shrewd fjord
#

header={'Authorization': 'Bot (bot token here)'}

harsh orbit
#

with () or without?

shrewd fjord
#

Without

harsh orbit
#

worked thx

#

& how to edit this message?

shrewd fjord
#

Np :)

#

Ah sec

shrewd fjord
#

Its the same, just use patch instead of post, and get the message id from the r.json() after creating a msg

harsh orbit
#

Thx

shadow vigil
#

this channel was sus for moment

glad cradle
#

someone said sus

shrewd fjord
#

Who

glad cradle
#

you sugey

shrewd fjord
naive briar
cyan eagle
#

Where can i host a discord bot 24/7 free

#

!hosting

unkempt canyonBOT
#
Discord Bot Hosting

Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.

See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.

You may also use #965291480992321536 to discuss different discord bot hosting options.

shrewd apex
#

u need a credit card at minimum

#

almost all big service providers require one even for free trial

cyan eagle
#

Umm, i already started hosting in raplit but ty for response

shrewd apex
cyan eagle
naive briar
#

I'd just local host at that point

cyan eagle
#

I dont have a computer

#

/ laptop

final iron
#

Then you're out of luck

#

buy one

glad cradle
cyan eagle
#

Btw can j host 2 or 3 bots jn same code if yes then how

dusk shadow
#

so, im prob gonna trigger some people here...

but is it ok to have your ᵉⁿᵗᶦʳᵉ bot on one .py file? p_shy

slate swan
#

Ok: yes
Should be done like that: definitely not

dusk shadow
#

soooooo

#

i mean, its not too bad, theres not like, too many features to it, or like, crazy insane/complex code.
i WANT to make it organised, but im totally new to this, and havent had any good teaching to tell me how to make it better...

#

the file is only, 555 lines. :/

glad cradle
#

well it's not that bad

dusk shadow
#

righttttt, thats why i was like, its not TOO bad... just not the best

#

would anyone have like, a couple of hours to spare to help me/teach me maybe split it up?

#

or an hour, if it takes that long?

cyan eagle
shrewd apex
cyan eagle
slate swan
#
import discord
from discord.ext import commands
from discord.ui import View, Button

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

    @commands.command()
    async def wheel(self, ctx):
        view = View()
        button = Button(label="WHEEL 🎡", style=discord.ButtonStyle.primary)

        @button.callback
        async def button_callback(interaction):
            try:
                await interaction.followup.send("CONGRATS DM TO @MLXLO TO CLAIM UR AWARD!", ephemeral=True)
            except Exception as e:
                print(f"Failed to send ephemeral message: {e}")

        view.add_item(button)
        await ctx.send(embed=discord.Embed(description="Click the button below when done!"), view=view)

async def setup(bot):
    await bot.add_cog(Wheel(bot))

Error:

C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py:235: RuntimeWarning: coroutine 'Item.callback' was never awaited
 ret = await coro(*args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
#

Anyone know how to fix ?

#

You don't set the callback with @button.callback but with button.callback = ... or by using views correctly.

#

hm let me try

#

code:

import discord
from discord.ext import commands
from discord.ui import View, Button

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

    @commands.command()
    async def wheel(self, ctx):
        view = View()
        button = Button(label="WHEEL 🎡", style=discord.ButtonStyle.primary)

        async def button_callback(interaction):
            try:
                await interaction.followup.send("CONGRATS DM TO @MLXLO TO CLAIM UR AWARD!", ephemeral=True)
            except Exception as e:
                print(f"Failed to send ephemeral message: {e}")

        button.callback = button_callback 
        view.add_item(button)
        await ctx.send(embed=discord.Embed(description="Click the button below when done!"), view=view)

async def setup(bot):
    await bot.add_cog(Wheel(bot))
#

Error:
Failed to send ephemeral message: 404 Not Found (error code: 10015): Unknown Webhook

#

Thank you i changed
This line : ```py
await interaction.followup.send()

To ```py
await interaction.response.send_messag()```
this

And it worked
cyan eagle
glad cradle
sharp bay
#
#import required files
import discord
from discord.ext import commands

#import bot token
from apikey import *

intents = discord.Intents.default()
intents.members = True


client = commands.Bot(command_prefix ='!', intents=intents)

#EVENTS

@client.event
async def on_ready():
    print("Bot is ready!")
    print("-------------")

@client.event
async def on_member_join(member):
    channel = client.get_channel(1172178888844128298)
    await channel.send("Hello Obama")
    

#COMMANDS

@client.command()
async def rares(ctx):
    await ctx.send('Rares')

@client.command()
async def shutdown(ctx):
    await ctx.send('Shutting Down...')
    print('-------------')
    print('Bot is shutdown')
    print('-------------')
    await client.close()


client.run(BOTTOKEN)``` could anyone review this code? My bot is starting but not replying to commands
sick birch
sharp bay
#

would it change anything?

sick birch
#

You technically can but you should use only the intents you need

sharp bay
#

oh ok

#

didnt know thanks

glad cradle
#

it increases the ram eaten by the Bot as well (related to what Robin said)

sharp bay
#

wait so the shutdown command isnt working. Do I need to shutdown my pc to get the bot offline?

sick birch
sharp bay
#

and when I save the file it doesnt save until I shutdown the bot

sick birch
#

If you make changes to your code it doesn't automatically get applied

#

"Hot-reloading," it's called

sharp bay
#

yeah do I need to shutdown my pc so the bot goes offline too?

sick birch
#

No. await client.close() will disconnect your bot from Discord

sharp bay
#

in the terminal?

sick birch
sharp bay
sick birch
#

What makes you say it isn't working?

sharp bay
#

because I didnt add intents.message_content to reply to message i think

sick birch
# sharp bay

Stop the bot by going into your terminal, and hitting CTRL + C. Then re-run it

sharp bay
#

its still online

sick birch
#

Can you send a screenshot?

sharp bay
sick birch
#

And send a screenshot

sharp bay
sick birch
#

Cool. Your Python file is saved, yes?

sharp bay
#

ye

sick birch
#

And if you run it again, the !shutdown command still doesn't work?

sharp bay
#

doesnt

#

op

#

worked thanks

cold oyster
#

How do I make a event (discord server event)?

tardy crater
cold oyster
#

Make a discord server event

tardy crater
#

Your bot needs to be in a server to catch any events from it so that wouldn't be possible sadly

#

@cold oyster

cold oyster
#

It's a discord bot?

tardy crater
cold oyster
#

😭

#

I am saying make a DISCORD SERVER event

#

Not client.event

tardy crater
#

So what would trigger the event?

cold oyster
# tardy crater So what would trigger the event?

Learn How to Create Event on Discord

👉 Consider subscribing if this helped you out: https://www.youtube.com/channel/UC101jjIv-tkdPmAc4dJozvQ?sub_confirmation=1

► Join The Discord Community: https://discord.gg/CGHMv7TuxE

🔐 Protect Yourself Online & Unlock Loads of New Content On Your Streaming Services!

👉 https://go.nordvpn.net/aff_c?offer_i...

▶ Play video
#

I want to create THIS

#

With the BOT

glad cradle
#

!d discord.Guild.create_scheduled_event

unkempt canyonBOT
#

await create_scheduled_event(*, name, start_time, entity_type=..., privacy_level=..., channel=..., location=..., end_time=..., description=..., image=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a scheduled event for the guild.

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

New in version 2.0.
tardy crater
#

ohhh right i understand what you mean

tardy crater
slate swan
#

Code^

import discord
from discord.ext import commands
import configparser
import datetime
import pytz

config = configparser.ConfigParser()
config.read('./data/database.ini')

class InviteTracker(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        if 'INVITES' not in config:
            config['INVITES'] = {}

    @commands.command()
    async def set(self, ctx, channel: discord.TextChannel):
        config['INVITES']['CHANNEL'] = str(channel.id)
        with open('./data/database.ini', 'w') as configfile:
            config.write(configfile)
        await ctx.send(f"The invite channel has been set to {channel.mention}.")

    @commands.Cog.listener()
    async def on_member_join(self, member):
        guild_id = str(member.guild.id)
        channel_id = config.get('INVITES', 'CHANNEL', fallback=None)
        if channel_id:
            channel = self.bot.get_channel(int(channel_id))
            invites = await member.guild.invites()
            recent_invites = sorted(invites, key=lambda invite: invite.created_at, reverse=True)

            for invite in recent_invites:
                time_difference = (datetime.datetime.now(pytz.UTC) - invite.created_at.astimezone(pytz.UTC)).total_seconds()
                if time_difference < 60:
                    if invite.inviter and not invite.inviter.bot:
                        invite_uses = invite.uses
                        await channel.send(f"{member.mention} has been invited by {invite.inviter.mention} and has now {invite_uses} invites.")
                        break
                    else:
                        await channel.send(f"{member.mention} has joined using a vanity invite.")
                        break

async def setup(bot):
    await bot.add_cog(InviteTracker(bot))
slate swan
#

anyone know why it doesnt send invite msg

tardy crater
#

is this discordpy or pycord?

slate swan
modern whale
#

!e

# This example requires the 'message_content' intent.

import discord

intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

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

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

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

client.run('your token here')
shrewd fjord
#

I suggest you to use this instead

#

!pip DiscordUtils

unkempt canyonBOT
shrewd fjord
#
import discord
from discord.ext import commands
import DiscordUtils

intents = discord.intents.default()
intents.members = True
bot = commands.AutoShardedBot(command_prefix=">", intents=intents)
tracker = DiscordUtils.InviteTracker(bot)

@bot.event
async def on_member_join(member):
    inviter = await tracker.fetch_inviter(member) 

Its simple as that

#

Outdated tho ☠️☠️

sick birch
#

There's not much reason to make invite trackers anymore tbh, since discord has it built in

shrewd fjord
#

Yeah, xd but dont really have too much info

#

Like, rejoin, fake, and some stuff

naive briar
shrewd fjord
vapid parcel
#

Anyone know a good library or something that supports a lot of games for a game server monitor bot?

#

or you gotta do everything manually :/

#

I got one working of Minecraft but like, there are so many games, it would be a pain to do them all manually..

#

discord.errors.HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token

golden portal
#

interaction.followup is a webhook specifically for responding to interaction, it would be raising that error if you haven't responded to the interaction or if the webhook expired

#

yes, it lasts 15 mins

#

coding issue
sorry i mean you could just use channel.send if it's over 15 minutes

#

you will not have ephemeral though

#

that timeout is for your View instance, basically means, if you dont set a timeout on your View object, it will automatically be set to 15 minutes, you can set it yourself by assigning View.timeout

#

pretty much what i would do as well yea

#

welcoem

final iron
#

Perfect time to refer to the docs

#

So

#

!d discord.Interaction.channel

unkempt canyonBOT
final iron
#

You can see the returning types could either be a guild channel, private channel or thread

#

If it's a private channel it'll be a DM, if its a guild channel it'll be inside the guild

#

Why would it?

final iron
#

Well yeah, it will but TextChannel.send() doesn't use a webhook

#

The bot itself will be sending the message

#

Probably what I would do as well

#

You could implement an if statement to check if the webhook is still valid, and if it isn't just send it to the channel directly

#

channel isn't defined, but that's the gist of it

#

You shouldn't have a bare exception as well

#

Catch specific errors and handle them accordingly

#

Depends on a lot of factors

#

You have to respond within 3 seconds, so if your latency is extremely high you'll want to defer anyway

#

Also the whole await channel.send(f"The download link is broken or unavailable. Error details: {e}") doesn't really make sense. What benefits does sending the error message itself to the user provide?

shrewd fjord
final iron
#

Alright

#

I'd create an actual error handler for the command that processes everything

shrewd fjord
#

Getting GPT vibe CH_IconAlert

final iron
#

Unfortunately yeah

shrewd fjord
#

😔

final iron
shrewd fjord
#

Start by learning python not making a discord bot dead

final iron
#

I also have it internally log the error with information like the time it occured at, whether it's in a guild or DM channel, the specific command and the inputted arguments

shrewd fjord
#

And if already know python then checkout the docs and learn how stuff works

final iron
#

Just makes debugging a lot easier if you know the output and can recreate it

shrewd fjord
#

Imagine the handler triggered because of a global ratelimit and while in the ratelimit bot tries to send the error in log channel makes it worse ☠️ i had had this issue once, then it was like in a forever loop lol

final iron
#

I just created some commands to help debug

#

Clear my logging file, send the last specified lines, send the entire file

#

Search for specific text and retrieve the corresponding lines

#

I also have a task checking how often the file is being written to and sending me a message if it's past the limit I sent

#

I just have that setup in-case there's a major error that need fixing immediately

shrewd fjord
robust fulcrum
#

guys i have made this cogs watcher, it works fine for me , should i add something more to this delete event?

                        if (ext_path.suffix == ".py") & (
                            ext_path.stem.split("_")[-1] == "ext"
                        ):
                            if change_type == Change.deleted:
                                dotted_path = self.get_dotted_cog_path(ext_path)
                                print(dotted_path)
                                if dotted_path in self.bot.extensions:
                                    try:
                                        await self.bot.unload_extension(dotted_path)
                                        print(
                                            f"[bold red]Unloaded {dotted_path}[/bold red]"
                                        )
                                    except Exception as e:
                                        print(
                                            f"[bold yellow]⊢»[/bold yellow][bold red]{e}[/bold red]"
                                        )
                                        continue
shrewd fjord
#

Dk xd

trim barn
final iron
#

Yes, and has always been

trim barn
final iron
#

Development was stopped for a year, and it was completely functional during that time

sharp bay
#

does anyone have a website for discord.py libraries

brazen raft
#

It's only one library

#

Are you referring to its dependencies?

sharp bay
#

like the commands I meant

fiery girder
sharp bay
#

like intents = discord.message_content

#

things like this

brazen raft
ruby valve
#

module 'discord.app_commands' has no attribute 'has_permissions'

First time working with slash commands whats the new way to allow commands to only be used by people with certain permissions?

brazen raft
#

Via Discord application permission settings

#

Or whatever the setting section is called

#

Server administrators set permissions for users/roles to use application commands

#

When server administrators manage permissions in the server settings, unpermitted commands are also hidden from members

sharp bay
#
#import required files
import discord
from discord.ext import commands
from discord import Member
from discord.ext.commands import has_permissions, MissingPermissions


#import bot token
from apikey import *

intents = discord.Intents.default()
intents.members = True
intents.message_content = True


client = commands.Bot(command_prefix ='!', intents=intents)

#EVENTS

@client.event
async def on_ready():
    await client.change_presence(status=discord.Status.do_not_disturb, activity=discord.Game('Mamaliga Cu Carnati'))
    print("Bot is ready!")
    print("-------------")

    

#COMMANDS

@client.command()
async def shutdown(ctx):
    await ctx.send("Shutting Down...")
    await client.close()

@client.command()
@has_permissions(kick_members=True)
async def kick(ctx, Member: discord.Member, *, reason=None):
    await Member.kick(reason=reason)
    await ctx.send(f'User {Member} has been kicked')

@kick.error
async def kick_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You don't have permission to kick people!")

@client.command()
@has_permissions(ban_members=True)
async def ban(ctx, Member: discord.Member, *, reason=None):
    await Member.ban(reason=reason)
    await ctx.send(f'User {Member} has been banned')

@ban.error
async def ban_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You don't have permission to ban people!")
    


#RUN THE BOT
client.run(BOTTOKEN)``` why my bot doesnt kick or ban peopel
fiery girder
#

intents

#

or permission

fiery girder
fiery girder
#

and check if your bot have permission to ban and kick on your discord server

sharp bay
#

ok

brazen geyser
#

Hey guys, im remaking my /purge command and im getting this error, can someone help me fix that please:
Command 'purge' raised an exception: AttributeError: 'async_generator' object has no attribute 'flatten'
If you want, I can send that code, i was doing it from tuto

slate swan
#

!D discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the destination’s message history.

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

Examples

Usage...
slate swan
#

there is an example how to flatten into a list now

brazen geyser
#

thankss

glad cradle
glad cradle
#

yes, i asked why

slate swan
#

cause there was already a "built in" solution for that in python

#

so why implement it

glad cradle
#

4 fun

slate swan
glad cradle
#

don't blah me

#

turtle

slate swan
shrewd fjord
surreal yoke
#

When i'm trying to install py-cord-dev, i don't have any error but i have this message :

PS C:\Users\chris\Downloads\Btz - Public> pip install py-cord-dev
Collecting py-cord-dev
  Using cached py_cord_dev-2.5.0rc5-py3-none-any.whl.metadata (6.7 kB)
Requirement already satisfied: aiohttp<3.9.0,>=3.6.0 in c:\users\chris\appdata\local\programs\python\python311\lib\site-packages (from py-cord-dev) (3.8.6)
Requirement already satisfied: attrs>=17.3.0 in c:\users\chris\appdata\local\programs\python\python311\lib\site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord-dev) (23.1.0)
Requirement already satisfied: charset-normalizer<4.0,>=2.0 in c:\users\chris\appdata\local\programs\python\python311\lib\site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord-dev) (3.3.2)
Requirement already satisfied: multidict<7.0,>=4.5 in c:\users\chris\appdata\local\programs\python\python311\lib\site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord-dev) (6.0.4)
Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in c:\users\chris\appdata\local\programs\python\python311\lib\site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord-dev) (4.0.3)
Requirement already satisfied: yarl<2.0,>=1.0 in c:\users\chris\appdata\local\programs\python\python311\lib\site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord-dev) (1.9.2)
Requirement already satisfied: frozenlist>=1.1.1 in c:\users\chris\appdata\local\programs\python\python311\lib\site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord-dev) (1.4.0)
Requirement already satisfied: aiosignal>=1.1.2 in c:\users\chris\appdata\local\programs\python\python311\lib\site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord-dev) (1.3.1)
Requirement already satisfied: idna>=2.0 in c:\users\chris\appdata\local\programs\python\python311\lib\site-packages (from yarl<2.0,>=1.0->aiohttp<3.9.0,>=3.6.0->py-cord-dev) (3.4)
Using cached py_cord_dev-2.5.0rc5-py3-none-any.whl (1.1 MB)
Installing collected packages: py-cord-dev
Successfully installed py-cord-dev-2.5.0rc5

And when i'm trying to execute the code "discord" is not found in import discord

#

Anyone can help me?

brazen raft
#

Unless you have a good reason to use that fork

surreal yoke
brazen raft
#

Why

robust fulcrum
#

guys where should i close my db connections in discord.py

brazen raft
#

In your shutdown command or whatever

#

If you've subclassed the bot or client classes, doing so only in the close method suffices

meager rock
#

if you're using a sql based database, a pool is the better way to go, keeping connections open is memory consuming process

brazen raft
#

The database server uses memory anyway

#

I don't see how a connection pool solves this problem anyway

#

I think it isn't a problem to begin with

#

The database server needs to be able to serve as long as there are established connections

robust fulcrum
brazen raft
#

It gets called by __aexit__ unless you call it beforehand explicitly

brazen raft
#

I meant to type 👍 but I typed something which reacted to your message with that

#

Now I'll spend the next few minutes figuring out what I typed

#

Apparently +👍

robust fulcrum
final iron
robust fulcrum
brazen raft
#

Application commands seem nicer than message commands

naive briar
robust fulcrum
#

i thought making both prefix and slash would be a good ux

brazen raft
#

Discord users should adapt to application commands already

#

Discord is trying to improve those

robust fulcrum
#

kk, ty

brazen raft
#

It's just that there is a limit to how many application commands you can register

spark nimbus
#

well i get this error:

FileNotFoundError: [WinError 3] The system cannot find the path specified: 'cogs'

thats my code:

from discord.ext import commands
from discord import app_commands
from discord.ui import Button, view
from settings import *

client = commands.Bot(command_prefix="." , intents=discord.Intents.all())

client.remove_command('help')

@client.event
async def on_ready():
    print(f'Connected as {client.user}\nDiscord.py version: {discord.__version__}\nPython version: {platform.python_version()}')
    synced = await client.tree.sync()
    print(f'CMD synced: {str(len(synced))}')

async def load():
    for filename in os.listdir('cogs'):
        if filename.endswith('.py'):
            await client.load_extension(f'cogs.{filename[:-3]}')
            print(f'{filename[:-3]} is ready to use!')


async def main():
    async with client:
        await load()
        await client.start(token)

asyncio.run(main())```
it worked until now idk what happend]
final iron
robust fulcrum
#

guys why i getting guild not found even it exists?

    async def sync_slash_commands(self, guilds: int):
        guild = self.get_guild(guilds)
        if guild:
            self.tree.copy_global_to(guild=guild)
            await self.tree.sync(guild=guild)
        else:
            self.bprint(
                f"[bold red]Failed to sync slash commands to guild {guilds}[/bold red]"
            )
spark nimbus
final iron
unkempt canyonBOT
#

get_guild(id, /)```
Returns a guild with the given ID.

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

Provide an absolute path then

surreal yoke
spark nimbus
final iron
robust fulcrum
#

Sry for skull emoji , mistyped

final iron
spark nimbus
#

E:\python\discord\bot

final iron
surreal yoke
spark nimbus
upbeat blade
#

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

You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#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).
final iron
#

All the control is abstracted away from the user

#

You pretty much control which embeds are being passed. Thats it

#

Creating your own paginator is extremely easy as well

#

That’s the entire problem with PyCord and why it’s the least popular fork. All the control is taken away from the user in the name of “ease of use”, when it actually makes doing anything above surface level incredibly difficult

surreal yoke
#

I'm beginner

surreal yoke
final iron
spark nimbus
final iron
#

You never asked a question

#

You gave your file path and didn’t ask any question

final iron
#

I already told you, provide an absolute path

robust fulcrum
turbid condor
brazen raft
#

It ended already

final iron
robust fulcrum
turbid condor
#

I'm late then ig

brazen raft
robust fulcrum
#

Ye but why do i get error guild not found
I am curious

robust fulcrum
turbid condor
#

Your id might be wrong

final iron
#

It’s not in the bots cache

robust fulcrum
#

I copied from my guild and pasted

turbid condor
#

Or you might be using wrong datatype

slate swan
#

The one pappy is using what program is that

robust fulcrum
#

Ctrl+c , Ctrl+v

brazen raft
robust fulcrum
robust fulcrum
#

Ill change

final iron
#

Why doesn’t it matter

robust fulcrum
#

.

turbid condor
#

Well cache does matter in case of get_guild

robust fulcrum
#

Hmm

#

Why it don't fetch guild then

turbid condor
#

If you are using fetch_guild then that's another matter

robust fulcrum
#

Is it lazy 🦥

final iron
brazen raft
robust fulcrum
#

Oh

#

Never expected this

#

Ty all

brazen raft
#

Make sure you use the command with an ID of a guild your bot is actually in

shrewd fjord
#

Snipy be searching for rule 9

slate swan
#
    import discord
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\__init__.py", line 23, in <module>
    from .client import *
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 1, in <module>
    from discord import Interaction, Message, Attachment, MessageType, User, PartialMessageable, Permissions, ChannelType, Thread
ImportError: cannot import name 'Interaction' from partially initialized module 'discord' (most likely due to a circular import) (C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\__init__.py)```
#

anyone knows the reason

#
import discord
import requests
import asyncio
import random
import configparser
from discord.ui import View, Button
from discord.ext import commands```
#

Do you have a file named discord.py

#

no

#

Show the file structure of your project

slate swan
#

cause it works on my vps

#

That has nothing to do with rate limits

#

That's an issue with the imports, your bot isn't even starting in the first place

#

i did too many attemps

#

Again, no

sick birch
#

Tracebacks are usually larger than this

sick birch
#

Hrm

slate swan
#

Python 3.9.7

sick birch
brazen raft
sick birch
slate swan
#

it works on my vps but it doesnt work on my main pc

brazen raft
sick birch
#

Not the Python version

slate swan
#

it was worked a minute ago when i restarted it said that

sick birch
#

Hmm

brazen raft
slate swan
#

on my vps it is 2.2.0 should i try that version

brazen raft
sick birch
#

Roie, I think you're right

unkempt canyonBOT
#

discord/client.py line 1

"""```
sick birch
#

This is line 1 of client.py

slate swan
sick birch
#

The traceback indicates this:

  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 1, in <module>
    from discord import Interaction, Message, Attachment, MessageType, User, PartialMessageable, Permissions, ChannelType, Thread
#

And this is not how discord.py does internal imports

brazen raft
slate swan
#

ok

brazen raft
#

pip uninstall discord

slate swan
#

still same

brazen raft
#

You can see its summary says "A mirror package for discord.py. Please install that instead"

#

What's the output of pip list

sick birch
#

@slate swan uninstall discord.py, and re-install it

brazen raft
#

And are you sure you're uninstalling it from the right pip?

sick birch
#

Seems like corrupted file maybe

#

discord/client.py has the wrong contents in it

slate swan
#

aight let me try

slate swan
#

yeah

#

it worked thanks

calm vector
#

There's a question at #1173304580445065216 about slash commands that I'm not sure I can answer. The dpy API reference doesn't mention the classes that the asker is trying to import.

slate swan
#

`Traceback (most recent call last):
File "C:\Users\abhay\OneDrive\Desktop\ \botx helper\main.py", line 21, in <module>
@bot.hybrid_command(name="bitcoin", description="Shows BotX Bitcoin address")
^^^^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'hybrid_command'

(venv) C:\Users\abhay\OneDrive\Desktop\ \botx helper>`

#

anyone plz help

#

im using bot.hybrid_command

slate swan
#

!pastebin

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

slate swan
#

canu help

#

what error

#

i doubt any1 can looks suspicious about that crypto

slate swan
#

crypto addy

slate swan
#

im facing and how to fix??

#

show pip packages

slate swan
#

yea you literally installed almost every discord library there is

naive briar
#

Is this related to Discord bots?

slate swan
slate swan
brazen raft
#

And get rid of the rest

slate swan
brazen raft
#

Only the ones you installed for Discord botting I mean

slate swan
#

other packages

brazen raft
#

pip uninstall package1, package2, etc.

slate swan
#

oke

brazen raft
#

Although instead of doing all that

#

I recommend just using a virtual environment and not messing it up

#

Even if you do install many things which you don't need, you can recreate a virtual environment and install only packages which you need

slate swan
brazen raft
#

Did you configure your virtual environment beyond installing packages?

brazen raft
#

Could you simply configure them in a new virtual environment?

#

The virtual environment is just a folder

slate swan
#

ik

brazen raft
#

It shouldn't include any of your project files

brazen raft
slate swan
brazen raft
#

Then yeah just recreate a virtual environment, apply the configurations and pip install discord.py

brazen raft
#

Do you know how to activate virtual environments?

slate swan
brazen raft
#

That's not how you activate venv

slate swan
brazen raft
#

It's how you create that virtual environment's folder

brazen raft
#

Inside venv you're going to see a Scripts folder if you're on Windows

#

That folder contains scripts named activate

slate swan
brazen raft
#

You need to run that before trying to install packages

brazen raft
#

Ok

brazen raft
slate swan
slate swan
# brazen raft Did it finish already

python main.py [2023-11-12 23:16:55] [INFO ] discord.client: logging in using static token [2023-11-12 23:16:58] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 70414257be5715b592ebc9c745787875).

#

worked ty

polar skiff
#

please help, someone can write code for tickets with buttons. And how to put a bot to work 24/7?

slate swan
final iron
static imp
#

anyone here familiar with discord bots making discord bots? or how we can possibly do this?

fading marlin
#

Well, first of all you kinda need a bot token to create a new Discord bot. So, ethically speaking, bots cannot make more bots without human intervention (creating the bot application itself and getting the token)

static imp
vapid parcel
#

Best sqlite editor?

drifting arrow
#

I am trying to run a discordbot on a private machine but I keep getting this error:

aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')]

I ran python3 --version and got no response but when I did python --version my python version is 3.10.8

Anybody have any idea how I can fix this?

acoustic kernel
#

Anyone have good sample bot code I can look at

mortal zenith
acoustic kernel
final iron
final iron
robust fulcrum
#

Guys why do many people use bot.start instead of bot.run ,is there any major difference or benefit?

final iron
#

!d discord.ext.commands.Bot.start

unkempt canyonBOT
#

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

A shorthand coroutine for [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login) + [`connect()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.connect).
final iron
#

!d discord.ext.commands.Bot.run

unkempt canyonBOT
#

run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., root_logger=False)```
A blocking call that abstracts away the event loop initialisation from you.

If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.start) coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.connect) + [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login).

This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.

Warning

This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
vale prairie
#
@tree.command(guild=discord.Object(id=id_do_servidor), name="convidar", description="Convide um membro")
async def setup(interaction: discord.integrations, cargo: discord.Role, membro: discord.Member):
    
    if discord.utils.get(interaction.user.roles, id=id_cargo_coroas):
        # Verifica se o membro já possui o cargo
        if cargo in membro.roles:
            await interaction.response.send_message(f"{membro.mention} já possui o cargo {cargo.mention}.", ephemeral=True)
        else:
            # Adiciona o cargo ao membro
            await membro.add_roles(cargo)
            await interaction.response.send_message(f"{membro.mention} foi convidado para o cargo {cargo.mention}!", ephemeral=True)
    else:
        await interaction.response.send_message("Você não é dono de alguma Corp ou Org", ephemeral=True)```

How do I select just a few specific positions in the call when typing the command?
#

It's getting all the positions on the server, how do I put it so that only a few positions appear?

final iron
#

cargo: discord.role isn't a valid converter

#

It's getting all the positions on the server, how do I put it so that only a few positions appear?
Which positions? The roles?

vale prairie
#

Like this, I'm creating a command to set specific positions, but positions are appearing, including those of founder, which is the position that has the most functions

#

I've tried to leave them below but it won't work, they still appear

final iron
#

Where are they appearing?

vale prairie
final iron
#

Yeah that's what happens when you typehint as a Role

#

You'll need to use choices instead then

#

View Documentation (has examples)
Option 1: typing.Literal
This is the easiest.```py
from typing import Literal

@...command(...)
async def choosecolour(
interaction: Interaction,
colour: Literal["Red", "Green", "Blue"]
):
print(colour) # will print either Red, Green or Blue

**Option 2: @app_commands.choices**```py
from discord import app_commands

@...command(...)
# name is shown to the user and value is returned to you.
# value can be of type str, int or float.
@app_commands.choices(
  colour=[ # param name
    app_commands.Choice(name="Red", value="red"),
    app_commands.Choice(name="Green", value="green"),
    app_commands.Choice(name="Blue", value="blue")
  ]
)
async def choosecolour(
  interaction: Interaction,
  colour: Choice[str] # [str] denotes the value type, not required.
):
  print(colour) # will print the chosen Choice obj
  # colour.name for the name and colour.value for the value you set

Option 3: enum```py
from enum import Enum

class Colours(Enum):

format: name - value

Red = "red"
Green = "green"
Blue = "blue"

@...command(...)
async def choosecolour(
interaction: Interaction,
colour: Colours
):
print(colour) # will print our enum. in this case, the Colour class above

colour.name for the name and colour.value for the value you set

#

Role will display all of the servers roles

#

choices will allow you to set which roles people can choose from

#

Option 2 (app_commands.choices) will most likely work the best in your situation if you want to code it dynamically

vale prairie
#

thanks

final iron
#

autocomplete is also an option as well

stone gate
#
    @discord.app_commands.command(name="frente_activo", description="Shows the current front.")
    async def frente_activo(self, interaction):
        await interaction.response.defer()
        general = self.db.Generals.find_one   ({"uid": str(interaction.user.id)})     
        division = self.db.Divisions.find_one({"general": general["name"]})
        if division is None:
            embed = discord.Embed(title="Error", color=0xf54242)
            embed.add_field(name="", value="No se encontró una unidad con ese ID.", inline=True)
            embed.set_footer(text="Path To Victory BETA 2")
            await interaction.followup.send(embed=embed)
            return
        embed = discord.Embed(title="Frente", color=0x44d63a)
        for line in ["frontline", "sideline", "backline"]:
            reserves = [unit for unit in division["units"] if unit["state"] == "Reserva" and unit["line"] == line]
            active = [unit for unit in division["units"] if unit["state"] == "Activa" and unit["line"] == line]
            embed.add_field(name=f"Reservas ({line})", value=len(reserves), inline=False)
            embed.add_field(name=f"Unidades Activas ({line})", value=len(active), inline=False)
        await interaction.followup.send(embed=embed, ephemeral=True)```

The command works as expected, but the messages it sends arent ephemeral at all, it doesnt matter if it is a normal message or an embed
#

is it because the response defer?

final iron
unkempt canyonBOT
#

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

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
robust fulcrum
shrewd fjord
#

Its just a coroutine you can use to start the bot

#

Unlike bot.run which internally calls asyncio.run

final iron
shrewd fjord
#

so if you just make something like
async def main():
some stuff
await ...start(..)
some moe stuff
asyncio.run(...) Wont bother you

#

But i don't think anyone uses start anyway ☠️

final iron
#

I do

#

It doesn’t block the event loop

shrewd fjord
#

For what reason? think

#

Yeah, but why would it bother you tho

final iron
#

I can run background tasks and other functions

#

I also get more control over logging

shrewd fjord
#

You can set your own format no?

#

You can pass logging handler in run method too think and about bg task, there is many way to create one on a blocking event loop, but yeah everyone has their own likings i wont complain Ops_ops

sick birch
shrewd fjord
#

Lets stop coding and play games :3

patent lark
#
thread_channel = get(guild.text_channels, topic=message.author.id)



        if thread_channel is None:
          # functionality```
thread_channel is returning NoneType. Even though its definitately there. Dont get it
#

could it be a cache related issue?

naive briar
#

You're trying to get a channel using the user's ID? How would that work?

patent lark
#

Im grabbing the channel that has the users id in the topic?

naive briar
#

No, topic of a channel will be a string, the author.id will be an int

patent lark
#

Ahhhh

naive briar
#

They're not the same

patent lark
#

Yes yes, so it returns None

#

i see.

#

So i can just slap this in an f-string

patent lark
#

What a noobie mistake, i shouldve checked the return type of discord.TextChannel.topic

#

Thanks for your help @naive briar

robust fulcrum
#

guys should i make a global app commands error handler or a app command handler for each command individually?

shrewd fjord
shrewd fjord
#

!d discord.ext.commands.Bot.tree

unkempt canyonBOT
#

property tree```
The command tree responsible for handling the application commands in this bot.

New in version 2.0.
robust fulcrum
shrewd fjord
#

Global is better imo, like sending specific error msg for specific errors xd

#

!d discord.app_commands.CommandTree.error

unkempt canyonBOT
#

@error(coro)```
A decorator that registers a coroutine as a local error handler.

This must match the signature of the [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.on_error) callback.

The error passed will be derived from [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError).
shrewd fjord
#

Finally ☠️

robust fulcrum
#

kk ,ty

#

do this work in exts also?

shrewd fjord
#

Um extension? Yes

#

But its different iirc, wait

robust fulcrum
#

i guess i can do self.bot.tree.on_error?

shrewd fjord
unkempt canyonBOT
#

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

A special method that is called whenever an error within an application command is dispatched inside this cog.

This is similar to [`discord.app_commands.CommandTree.on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.on_error) except only applying to the application commands inside this cog.

This **must** be a coroutine.
robust fulcrum
shrewd fjord
#

Specific cog

#

And for global just use @bot.tree.error deco

robust fulcrum
#

kk, ty

shrewd fjord
robust fulcrum
shrewd fjord
#

Um,, how tho SUS

robust fulcrum
sick birch
#

it has some quirks, by necessity

robust fulcrum
#

whats quirks?

shrewd fjord
#

Converters mainly

robust fulcrum
#

oh

#

i was making a clone of bookmark command of @lament depot

vale wing
#

Hybrid bad

shrewd fjord
#

Hybrid vegs aint bad :3

robust fulcrum
#

i can't use slash commands in message replies

sick birch
shrewd fjord
#

Um? What do you exactly mean

sick birch
#

Otherwise I would've done just that

shrewd fjord
#

^

robust fulcrum
shrewd fjord
#

You have to make explicitly

shrewd fjord
#

And yeah in hybrid command it will work (with prefix)

patent lark
#
user = await commands.MemberConverter.convert(ctx, thread_user_id)```

Says that argument parameter is missing.
#

ive printed thread_user_id. it returns the correct value

golden portal
patent lark
#

yes i have fixed it now

golden portal
#

tbf if you have the id, might as well just do guild.get_member

rigid hare
#

can my bot use another bot's slash commands? i wanna add a bunch of colours to the bot colour-chan,, and it would be much easier to code a quick command that grabs a list of colours from the internet instead of manually putting in like 50 colours

shrewd fjord
#

!pip matplotlib for colors

unkempt canyonBOT
shrewd fjord
#

!d matplotlib.colors

unkempt canyonBOT
#

A module for converting numbers or color arguments to RGB or RGBA.

RGB and RGBA are sequences of, respectively, 3 or 4 floats in the range 0-1.

This module includes functions and classes for color specification conversions, and for mapping numbers to colors in a 1-D array of colors called a colormap.

Mapping data onto colors using a colormap typically involves two steps: a data array is first mapped onto the range 0-1 using a subclass of Normalize, then this number is mapped to a color using a subclass of Colormap. Two are provided here: LinearSegmentedColormap, which uses piecewise-linear interpolation to define colormaps, and ListedColormap, which makes a colormap from a list of colors.

shrewd fjord
#

It has all css colors

robust fulcrum
#

guys is there any way i log when my bot send message/emebed/modal/anything else?

slate swan
#

Any cosutom bot developer dm pleae

grim rock
rugged shadow
plain pollen
# slate swan Any cosutom bot developer dm pleae

I saw you DM'ed me, and i know a little bit about discord bots, what's up? I don't make people bots, paid for or not, just so you know though (and we also just don't allow requests for paid work in this discord server at all)

bitter tundra
#

How do I sync application commands?

fresh notch
#

is it possible to reply to a message if i have the message id?

naive briar
#

Yes

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

Actually i don't think dpy has on_interaction opsi

#

Actually yes

#

!d discord.on_interaction

unkempt canyonBOT
#

discord.on_interaction(interaction)```
Called when an interaction happened.

This currently happens due to slash command invocations or components being used.

Warning

This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View) instead as it provides a nicer user experience.

New in version 2.0.
sick birch
#

you wouldn't get outgoing interactions with these

#

only responses

shrewd fjord
#

Uh, its just triggers when an interaction is created no?

slate swan
#

help

#

ok so im trying to make a list of commands when i prompt !help but the formating is all wrong

#

the list would print in like a code box format and the text is all wrong, plus there some extra text that i have no clue how it ended up there in the first place

#

Im thinking is due to the ctx but idk too much about it

slate swan
#

hello guys, do you know why are my commands aren't working ?
https://paste.pythondiscord.com/4POQ
they were working before but recently when i went for some test it wasn't working anymore

#

events are still working but for some reason commands aren't

flat solstice
#

Not sure if this might breach ToS but is there a way to scrape all of my user account DM history for all of my chats at once? I've looking for a specific user that I had a specific conversation with but I don't think they're in my DM history anymore so I don't have a way of finding them other than a few keywords from our conversation. So I'm wondering if there'd be a way to scrape all of my DM history for those keywords but I'm thinking it'd probably come under a client-user which I think is against ToS

glad cradle
#

yeah self bots break the ToS

void mauve
#

How do I add categories of the current guild as options to a discord.ui.View? I am passing categories list to the class and I need so every category was an option to choose

Following code seems to not be working

class SetupModal(discord.ui.View):
    def __init__(self, categories) -> None:
        super().__init__()

        for category in categories:
            self.add_option(discord.SelectOption(label=category.name, value=category.name))

    @discord.ui.select(
        placeholder="Choose a Category!",
        min_values=1,
        max_values=1,
    )
    async def select_callback(self, select: discord.ui.Select, interaction: discord.Interaction):
        embed = discord.Embed(title="Modal Results")
        embed.add_field(name="Selected Category", value=select.values[0])

        await interaction.response.send_message(embeds=[embed], ephemeral=True)
flat solstice
glad cradle
acoustic kernel
#

When i try to run an example discord bot i get this error message:

sick birch
acoustic kernel
#

dang i thought I update it

obsidian fable
#
def number_to_word(number):
    return ["one", "two", "three", "four", "five"][number-1]

button = ui.Button(emoji=f":{number_to_word(i)}:", style=discord.ButtonStyle.primary)

In components.0.components.0.emoji.name: Invalid emoji
etc...

what caused it, aren't number emotes :one:. :two:, :three: and so on?

shrewd fjord
shrewd fjord
#

Since one two are default you need to use unicode

obsidian fable
#

I see

shrewd fjord
#

\1️⃣

obsidian fable
#
1️⃣```

these right
shrewd fjord
#

!charinfo 1️⃣

unkempt canyonBOT
shrewd fjord
obsidian fable
#

tyty

shrewd fjord
#

:)

slate swan
#

thanks but what about the commands tho ?

static imp
#

!charinfo green

unkempt canyonBOT
gilded cedar
#

it's a pretty dumb situation but i want the buttons get disabled by the timeout
I've searched every solution on Github but they are irrevelant solutions to the problem
I tried use print function to see what's going on. it says "timeout success" however no buttons are disabled!
I'm using nextcord library btw
https://paste.pythondiscord.com/T56A

obsidian fable
#

can I use author.mention in interaction?

hushed galleon
# gilded cedar it's a pretty dumb situation but i want the buttons get disabled by the timeout ...

dunno if you've figured it out yet, but anytime you change your buttons you'll need to edit the message so discord knows what you've updated, for example: ```py
class MyView(discord.ui.View):
async def on_timeout(self):
for item in self.children:
item.disabled = True
# Store a previous interaction or the message beforehand
# so you can edit it:
await self.message.edit(view=view)

view = MyView()
view.message = await ctx.send(..., view=view)```

shrewd apex
#

so i always kept an interaction attribute also and updated it on interaction_check

#

iirc thats cause discord interaction components have that time validity

hushed galleon
#

yup, interactions expire after 15min, but as long as your timeout isn't 15min and you have the latest interaction you've received, it should be a reliable approach (also your only option if you don't have access to the channel)

shrewd apex
#

message and interaction are both needed then u can further use a try except along with it to edit

hushed galleon
shrewd apex
#

lmao it was pretty elusive and hard to recreate it took me a bit to figure this bug out in production

brazen geyser
#

hey guys is there any way to make that "Sun, August, 21, 2022, 06:19 PM" to like <t:1661098740:F> automatically?

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) for presentation within Discord.

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

If it's a datetime object pass it into this utility function

brazen geyser
#

so how should i add it?

slate swan
#

Pass .joined_at to util function

reef sonnet
#

Is it possible to use a loop to add items to select menus in pycord,
something like display user items

final iron
#

It’s possible in discord.py, but pycords implementation is shit

#

It’s possible with a list comp or a function

reef sonnet
#

what about nextcord?

final iron
#

Why does it matter

#

Which fork are you using

reef sonnet
final iron
#

Show how you’re doing it

reef sonnet
final iron
#

If you have no reasons to use pycord you should switch

#

discord.py has a larger support community, is 100x more popular than Pycord and has better implementations

reef sonnet
reef sonnet
final iron
#

it’s the same

#

It’s literally the same

final iron
#

You’re not adding any select options at all

reef sonnet
#

im adding them in the command code itself tho right?

@bot.slash_command(name='equip', description="Equip a player for PvP or matches")
async def equip_player(interaction: discord.Interaction):
    user_id = str(interaction.user.id)
    user_data = load_user_data()

    if user_id not in user_data or 'inventory' not in user_data[user_id]:
        await interaction.response.send_message("Your inventory is empty.")
        return

    base_players = user_data[user_id]['inventory']['players']['base']
    mid_players = user_data[user_id]['inventory']['players']['mid']
    max_players = user_data[user_id]['inventory']['players']['max']

    view = EquipPlayerView(user_id, base_players, mid_players, max_players)

    select_options = [
        discord.SelectOption(label=player, value=player) for player in base_players + mid_players + max_players
    ]


   view.add_item(discord.ui.Select(options=select_options))

   await interaction.response.send_message("Select 5 players to equip:", view=view)```
final iron
#

No

#

Look at the examples on how to create select menus

void mauve
#

How do I overwrite select menu from one to another? (Specifically I want to change the select menu of SetupModal class to a ChannelSelection)

class ChannelSelection(discord.ui.Select):
    def __init__(self, category):
        options = [discord.SelectOption(label=channel.name, value=str(channel.id)) for channel in category.channels]

        print(options)

        super().__init__(
            placeholder='Choose a channel',
            min_values=1,
            max_values=1,
            options=options
        )

    async def callback(self, interaction: discord.Interaction):
        item = self.values[0]
        await interaction.response.edit_message(content=f"You chose {item}! ", view=None, ephemeral=True)


class SetupModal(discord.ui.View):
    def __init__(self):
        super().__init__()

    @discord.ui.select(
        select_type=discord.ComponentType.channel_select,
        channel_types=[discord.ChannelType.category]
    )
    async def select_category(self, select, interaction: discord.Interaction):
        category_id = select.values[0].id
        category = discord.utils.get(interaction.guild.categories, id=category_id)

        channel_selection = ChannelSelection(category)

        await interaction.response.edit_message(view=channel_selection)

hushed galleon
# void mauve How do I overwrite select menu from one to another? (Specifically I want to chan...

one way would be to remove your select_category from the view and then add your new select menu, something like: py class MyView(discord.ui.View): @discord.ui.select(...) async def my_select(self, select, interaction): self.remove_item(select) self.add_item(AnotherSelect(xyz)) await interaction.response.edit_message(view=self) # The user can no longer use my_select()
or alternatively you can rewrite it as two views, which i usually find to be a cleaner approach: ```py
class SetupChannel(discord.ui.View):
def init(self, category):
super().init()
# After super().init(), you can update items by their method names:
self.on_select.options = [...]

@discord.ui.select(options=[], placeholder=...)
async def on_select(self, select, interaction):
    ...

class SetupCategory(discord.ui.View):
@discord.ui.select(...)
async def on_select(self, select, interaction):
view = SetupChannel(category)
await interaction.response.edit_message(view=view)```

vapid parcel
#
import discord

class ConfirmDeny(discord.ui.View):
    def __init__(self, ctx):
        super().__init__()
        self.ctx = ctx
        self.button_disabled = False

    @discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
    async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):
        if not self.button_disabled:
            self.button_disabled = True

            button.disabled = True 
            await interaction.response.send_message("Request accepted.", ephemeral=True)

    @discord.ui.button(label='Deny', style=discord.ButtonStyle.red)
    async def deny(self, interaction: discord.Interaction, button: discord.ui.Button):
        if not self.button_disabled:
            self.button_disabled = True

            button.disabled = True
            await interaction.response.send_message("Request denied.", ephemeral=True)
#

how to make it like, go grey/gray after the interaction? so no buttons are pressable at all..?

#

cuz disabled just makes it not work after the interaction... i just wanna make it to where its not possible to press..?

final iron
vapid parcel
#

No i mean like

#

where it just wont let you press it

vapid parcel
final iron
unkempt canyonBOT
south coyote
#

I fed the entire documentation for the Discord.PY API to ChatGPT last night and now I am cranking out bots like nobody’s business

sick birch
#

Is the code of good quality?

#

The documentation can tell you about individual pieces but there are a lot that go into making good bots aside from just the documentation

final iron
vapid zodiac
#

Skill issue if ive ever seen one

sullen roost
#

How do I connect my discord bot to Pinterest so that it can post pictures on one channel

#

Ping me

final iron
sullen roost
shrewd fjord
final iron
shrewd fjord
#

The pinterest api specifically, and then gather a client token and then do stuff

#

Pinterest api is a more of a headache to work with, i'd recommend using unsplash api

shrewd fjord
#

Yeah dead

elder locust
#

is there any way to end the deferred interaction thinking thing without sending a whole message

elder locust
#

Tragic

turbid condor
#

!d discord.Interaction.delete_original_response

unkempt canyonBOT
#

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

Deletes the original interaction response message.

This is a lower level interface to [`InteractionMessage.delete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.delete) in case you do not want to fetch the message and save an HTTP request.
shrewd fjord
#

Well for button, you can, but for slash command you cant

turbid condor
#

You can try using this at the end of your callback but not sure

#

Wait nvm it wont work

elder locust
#

is there anyway for the creation of a thread to be the interaction followup then?

shrewd fjord
#

Elaborate more please

elder locust
#

I have a command that creates a thread, and then sends a few files into that thread

shrewd fjord
#

Oh wait gotcha, no not possible

elder locust
#

tragic tragic

#

thanks anyways

shrewd fjord
#

One thing you can possibly do is

#

await inter.followup.send('done', ephemeral=True, delete_after=True)
I dont know how, but you can delete the ephemeral message

shrewd fjord
#

Ita basically 1.0 float loo

#

lol

#

Instead of writing 1.0 True looks cool opsi

glad cradle
#

or ~~True|1&1

#

and so on lmao

shrewd fjord
vale wing
shrewd fjord
#

!e
~~float('inf')

unkempt canyonBOT
#

@shrewd fjord :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     ~~float('inf')
004 |      ^^^^^^^^^^^^^
005 | TypeError: bad operand type for unary ~: 'float'
shrewd fjord
#

Ok idk

#

Xd

slate swan
#

hi

#

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

mortal kindle
#

hey, how can i edit an embed and files inside of it? for example, i have a embed created and i want to paginate it, when i move the page all i can do is get the file out of embed...

golden portal
mortal kindle
#

It worked! thanks a lot for the help

split fog
#

How do some bots play music via spotify, is there a package for that like yd_dlp for youtube?

grim rock
#

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

This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for non-interaction contexts.

For interaction based contexts this does one of the following...
tough lance
shrewd fjord
#

!pip wavelink

unkempt canyonBOT
shrewd fjord
#

Use this ig

south coyote
# split fog How do some bots play music via spotify, is there a package for that like yd_dlp...

Use Spotify API for Metadata Only:
You can use Spotify's API to get information about tracks, albums, and playlists.
Once you have the track information (like the name and artist), you can use another service (like YouTube) to search for and play a similar or the same track.
This method involves using yt-dlp or a similar tool to fetch the audio from a service that allows direct streaming (like YouTube), based on the track information obtained from Spotify.

Spotify Premium with an External Player:
    If you have Spotify Premium, you can control Spotify playback through their API.
    This method involves controlling a Spotify client (like one running on a server) and then capturing and streaming the audio output to Discord.
    This approach is technically complex and might not be entirely within the Spotify terms of service, as it involves capturing and re-streaming the audio.
#

Here's a simplified example of how you might use the Spotify API to get track information (you'll need to have spotipy, which is a Python library for the Spotify Web API):


import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

spotify_client_id = 'YOUR_SPOTIFY_CLIENT_ID'
spotify_client_secret = 'YOUR_SPOTIFY_CLIENT_SECRET'

client_credentials_manager = SpotifyClientCredentials(client_id=spotify_client_id, client_secret=spotify_client_secret)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

# Searching for a track on Spotify
track_results = sp.search(q='artist:Radiohead track:Creep', type='track')
track = track_results['tracks']['items'][0] if track_results['tracks']['items'] else None

if track:
    print("Track found on Spotify:", track['name'])
    # Use yt-dlp or similar to find the track on YouTube and play it

Important Notes:

To use Spotify's API, you need to register your application on the Spotify Developer Dashboard to get your client ID and secret.
Remember to abide by Spotify's terms of service when using their API, especially in terms of what you can and cannot do with the data you retrieve.
Directly streaming Spotify tracks in a Discord bot is against Spotify's terms of service, as it involves redistributing their content.
Always ensure that your implementation complies with legal requirements and the terms of service of both Spotify and Discord.
zealous sigil
#

<@&831776746206265384>

split fog
shrewd fjord
#

Same

plain pollen
#

we also don't help with anything using those tools, since they go against youtube's ToS

#

!yt-dl

unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
candid escarp
#

Did anyone make like an AI Ticket System/Chatbot before?

final iron
candid escarp
final iron
#

Example of what? Do you want a specific bot?

split fog
candid escarp
#

like a specific bot or a github repo

naive briar
obsidian fable
#
user = interaction.author
banner_url = user.banner.url
embed.set_image(url=banner_url)

is this the correct way to fetch user banner? doesnt seem to work for me.

brazen raft
#

It only works for client users

#

I mean, only for the client/bot you're programming. Not for other users

#

My bad, I'm talking nonsense

obsidian fable
#

its basically just a user info command, thats why interaction.author

brazen raft
obsidian fable
#

I see

brazen raft
#

Try fetching the interaction's user and seeing if that works

obsidian fable
#

alright

brazen raft
#

There should be no problem

obsidian fable
#

so interaction.user?

final iron
obsidian fable
#

ahhh

final iron
#

!d discord.Member.banner

unkempt canyonBOT
#

property banner```
Equivalent to [`User.banner`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.banner)
final iron
#

Docs are your friend

acoustic kernel
#

how do I createa role using a bot

slate swan
#
import discord
from discord.ext import commands

color = discord.Colour(int("e4741f", 16))
bot = commands.Bot(command_prefix="!")

@bot.event
async def on_ready():
    print(f"{bot.user} is ready and online!")

@bot.command()
async def test(ctx):
    sender = None
    receiver = None

    async def sender_callback(interaction):
        nonlocal sender
        sender = interaction.user.mention
        button._disabled = True 

    async def receiver_callback(interaction):
        nonlocal receiver
        receiver = interaction.user.mention
        button1._disabled = True 

    button = discord.ui.Button(label="I'm Sender", style=discord.ButtonStyle.gray)
    button1 = discord.ui.Button(label="I'm Receiver", style=discord.ButtonStyle.gray)

    button.callback = sender_callback
    button1.callback = receiver_callback

    embed = discord.Embed(
        title="User Identification",
        description=f"**Sender:**    **Receiver:** \n{sender}    {receiver}",
        color=color
    )

    view = discord.ui.View()
    view.add_item(button)
    view.add_item(button1)
    await ctx.send("test.")
    await ctx.send(embed=embed, view=view)

bot.run("Nope")

thank you could i also ask you something about the code sent?
it works but when i click the I'm Sender button it wont update the embed with my name
im expecting for the embed to say sender: @slate swan

final iron
unkempt canyonBOT
#

await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., display_icon=..., mentionable=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role) for the guild.

All fields are optional.

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

Changed in version 1.6: Can now pass `int` to `colour` keyword-only parameter.

New in version 2.0: The `display_icon` keyword-only parameter was added...
slate swan
#

nonlocal joeCollapse

final iron
acoustic kernel
#

Yeah Im looking at that right now if I want to create a roll the only thing I need to do is go:
await discord.Guild.create_role(name=role) ?

final iron
#

No

#

discord.py works heavily with the principal of OOP. You’ll need a discord.Guild object, and you’ll rarely initialise it yourself

acoustic kernel
#

how do I get that?

final iron
#

How you retrieve the discord.Guild object depends on where/how you’re executing the code

acoustic kernel
#

Well if it is only for personal use in one server how do I get this discord.guild object

final iron
#

No. Is it a command, event etc

acoustic kernel
#

oh

#

do you have an example?

final iron
acoustic kernel
#

Can I use that command if Im using slash coammands with the tree

final iron
#

With app commands it would be

slate swan
#

then its interaction.guild

final iron
#

!d discord.Interaction.guild

unkempt canyonBOT
acoustic kernel
#

so like this

await interaction.guild.create_role(name=role)

final iron
acoustic kernel
#

@bot.tree.command(name="role",description="Creates a new Role:")
async def role(interaction: discord.Interaction,role:str):
await interaction.guild.create_role(name=role)

final iron
#

what

final iron
acoustic kernel
#

what do you mean

slate swan
acoustic kernel
#

right now I am trying to make a command for players to "signup"
Where it creates a new role of the said name
Then assigns them to that role
Then creats a catergory and several channels only they have access to

final iron
final iron
acoustic kernel
#

Thats not a problem Im only running this with me and my friends server we have like 20 people max

slate swan
#

is there anyway to delete 1000 messages with bulk delete

final iron
unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages) to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) is also needed to retrieve message history.

Changed in version 2.0: The `reason` keyword-only parameter was added.

Examples

Deleting bot’s messages...
final iron
#

Only 100 messages are deleted at a time

slate swan
#

is there anyway to make it

final iron
#

make it what

slate swan
#

incrase delete limit

final iron
#

No

#

It’s a non issue though

#

I cannot see any situation where you will need to consistently delete 1000 messages extremely quickly

#

For 1000 messages it’ll probably take like 30-50 seconds

slate swan
#

what about that way

    async def delete_messages(self, channel):
        messages = [message async for message in channel.history(limit=None)]
        messages_to_delete = [message for message in messages if not message.pinned]

        while messages_to_delete:
            chunk = messages_to_delete[:100]
            messages_to_delete = messages_to_delete[100:]

            await channel.delete_messages(chunk)
            await asyncio.sleep(1)  ```
final iron
#

Let’s not take code off the internet please

#

That’s a terrible solution and will take even longer

final iron
#

It's impossible to get around

short shard
#
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
import json

app = Flask(__name__)
app.secret_key = ''  # Change this to a secure secret key

login_manager = LoginManager()
login_manager.init_app(app)``` what need to do on secrete key to make a link for the dashboard?
void mauve
#

Is it possible to filter out in a select menu to only show roles that are being used (more than 1 user has it) ?

Here's the code for the SelectMenu

class OpenBaseRolesSelection(discord.ui.View):
    def __init__(self, page=1):
        super().__init__()

    @discord.ui.select(
        select_type=discord.ComponentType.role_select,
        min_values=0,
        max_values=3,
    )
    async def on_select(self, select, interaction: discord.Interaction):
        global basic_roles

        basic_roles = []

        for role in select.values:
            basic_roles.append(role)

        mentioned_mod_roles = [role.mention for role in moderator_roles]
        showcase_mod_roles = ' '.join(mentioned_mod_roles)

        mentioned_basic_roles = [role.mention for role in basic_roles]
        showcase_basic_roles = ' '.join(mentioned_basic_roles)

        print(moderator_roles, basic_roles)

        await interaction.response.edit_message(content=None, embed=create_embed(title='Current configuration',
                                                                                 description=(
                                                                                     f'*Open Ticket Channel:* <#{open_ticket_channel_id}>\n'
                                                                                     f'*Save Transcripts Channel:* <#{save_transcript_channel_id}>\n\n'
                                                                                     f'*Moderator Roles Chosen:*\n{showcase_mod_roles}\n\n'
                                                                                     f'*Basic Roles Chosen:*\n{showcase_basic_roles}')),
                                                view=SetupConfirmation())
final iron
#

!d discord.ui.RoleSelect exists btw

unkempt canyonBOT
#

class discord.ui.RoleSelect(*, custom_id=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None, default_values=...)```
Represents a UI select menu with a list of predefined options with the current roles of the guild.

Please note that if you use this in a private message with a user, no roles will be displayed to the user.

New in version 2.1.
smoky cedar
#

I want to do integration testing on some of my slash commands. Can I create my own interaction object simulating my discord user? Or is it not possible?

slate swan
final iron
final iron
#

I'd look through it's code base

slate swan
#

thats the problem possibly

acoustic kernel
#

@bot.tree.command(name="role",description="Creates a new Role:")
async def role(interaction: discord.Interaction,role:str,):
created_role = await interaction.guild.create_role(name=role)
await interaction.response.send_message(f"Successfully created role: {created_role}")

If I want to specify the permissions for the role I created how do I do that

bitter tundra
#

How do I access the 'global_name' property of user in pycord

shrewd apex
#

!d discord.User.global_name

unkempt canyonBOT
clear lark
#

Is there a way to color slash command choices besides roles?

naive briar
#

No

mighty saffron
#

hey im having trouble making a button to close a ticket ( channel ) i used a lot of ways but its just doesnt work ( im using pycord)

#

it is changing the name

#

but not changing the perms

#
await interaction.channel.set_permissions(interaction.guild.default_role, send_messages=False)

tried that aswell

shrewd fjord
#

Use overwritea

#

Overwrites*

shrewd fjord
#

!d discord.TextChannel.edit

unkempt canyonBOT
#

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

Edits the channel.

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

Changed in version 1.3: The `overwrites` keyword-only parameter was added.

Changed in version 1.4: The `type` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead...
mighty saffron
#

ok lets see

shrewd fjord
#

Wait

#

Could you share full code? Full callback

mighty saffron
#

yyea

#

let me send u in dms i cant send it here

shrewd fjord
#

Uhh overwrites is mapping

mighty saffron
#

wdym

shrewd fjord
#

To use PermissionOverwrites for a channel, you can use them like a dictionary, as follows:

overwrites = {
  guild.default_role: discord.PermissionOverwrite(
    read_messages=False,
    send_messages=False,
  ),
  Role1: discord.PermissionOverwrite(
    read_messages=True,
    send_messages=True,
  )
}
await channel.edit(overwrites=overwrites)

Role1 is an instance of discord.Role. You can also use discord.Member objects for the keys here also

Here, found it

#

This is how you ise overwrites

mighty saffron
#

lets see

#

WORKING!!

#

LETS F GOOO

#

tysm bro

shrewd fjord
#

Np :3

main torrent
#

Healo

#

How to create discord bot 🫣

white citrus
#


class TicketSystem_Del(nc.ui.View):
    def __init__(self, guild_id, message_id, channel_id):
        super().__init__(timeout=None)
        self.guild_id = guild_id
        self.message_id = message_id
        self.channel_id = channel_id

        org_c = self.guild.get_channel(self.channel_id)
        org_m = await org_c.fetch_message(self.message_id)

        self.add_item(nc.ui.Button(style=nc.ButtonStyle.link, label="Jump to!", url=org_m.url))```
#

How do you do that in init?

white citrus
shrewd fjord
#

How are you initializing the view right now?

main torrent
shrewd fjord
#

?

main torrent
final iron
unkempt canyonBOT
#

await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., bypass_verification=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below...
final iron
#

roles kwarg

sharp bay
#

does anyone have any resource to learn discord bot programming in python?

final iron
void mauve
#

how do i add users to a thread that are have certain role automatically? something like overwrites for channels

final iron
#

!d discord.Thread.add_user

unkempt canyonBOT
#

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

Adds a user to this thread.

You must have [`send_messages_in_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.send_messages_in_threads) to add a user to a thread. If the thread is private and [`invitable`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread.invitable) is `False` then [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages) is required to add a user to the thread.
final iron
#

You can see when the user updates with

#

!d discord.on_member_update

unkempt canyonBOT
#

discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) updates their profile.

This is called when one or more of the following things change...
void mauve
#

or will it work to change some overwrites for the channel, so users with certain role can manage threads and look through all of them?

main torrent
final iron
#

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

You can get the default system channel with:

#

!d discord.Guild.system_channel

unkempt canyonBOT
#

property system_channel```
Returns the guild’s channel used for system messages.

If no channel is set, then this returns `None`.
main torrent
#

Haa

#

Thankz

#

How do like this

#

@final iron

#

You know

final iron
#

Like an embed?

main torrent
#

Yes

final iron
#

!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...
final iron
#

You’ll pass your Embed object into the embed kwarg when sending the message

main torrent
#

Timestamp means?

final iron
#

Try it and see

main torrent
#
class discord.Embed(*, colour=red, colour=red, title=non, type='rich', url=non, description=non,
timestamp=non)
final iron
#

What is non

main torrent
final iron
#

what

main torrent
final iron
#

You’ve said that, I know

#

What is non

#

You’ve passed it into 4 kwargs

main torrent
#

👀

main torrent
final iron
#

It’s an embed, and I already linked the docs

main torrent
#

?

final iron
#

I mean, it is called discord.Embed

main torrent
#

Bruh

#

How to create this

final iron
#

Like I already said, you create an embed

#

I’ve linked the docs on it

#

You’ll need to experiment to copy the embed you’ve shown

final iron
#

That’ll throw an error, but yeah

#

That’s the gist of it

main torrent
#

Ops

main torrent
final iron
#

what

#

What is a cap

main torrent
final iron
#

Yeah

#

Looks like they just used new lines for the description

main torrent
#

@final iron

#

Coustom status how do

unkempt canyonBOT
#
Huh? No.

No documentation found for the requested symbol.

slate parrot
main torrent
slate parrot
#

not sure though ¯_(ツ)_/¯