#discord-bots

1 messages · Page 285 of 1

urban parrot
#
                await basketballdb.commit()
                new_random_member = random.choice(client.team_two)
                for themember in client.team_two:
                    if themember == new_random_member:
                        await channel.set_permissions(themember, read_messages=True,send_messages=True)
                    else:
                        await channel.set_permissions(themember, read_messages=True,send_messages=False)
                print(x)

Don't ignore this and please help

opaque kelp
#

Did Discord recently become more severe regarding the ability for bots to simply read the chat? I've checked and my bot has all the permissions (administror) AND intents, yet suddenly (a few days) it can't read messages anymore. It detects them, but their content is empty.

hallow fog
#
    
    valid_chars = set("0123456789+-*/")
    
    
    in_number = False
    last_char = None
    has_operator = False
    
    for char in s:
        if char in valid_chars:
            if char.isdigit():
                if char == '0' and not in_number:
                    return False  
                in_number = True
            else:
                if not in_number:
                    return False  
                if has_operator:
                    return False  
                in_number = False
                has_operator = True
            last_char = char
        else:
            return False  
    
    if in_number:
        if last_char == '0':
            return False  
        return True  
    
    return has_operator  

user_input = input("Enter a string: ")


result = is_valid_expression(user_input)


print(result)```
opaque kelp
#

lemme check again

#

looks like it

#

this is from the OAuth2 tab

hallow fog
#

not working properly with more than 1 operator

naive briar
opaque kelp
#

No, do you have more info on that? I didn't know I had to also enable them in my code

naive briar
#

!d discord.Intents

unkempt canyonBOT
#

class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.

Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).

New in version 1.5.
opaque kelp
#

Thank you, I'll have a look

urban parrot
#

please do not ignore this.

cloud dawn
#

The issue is that I've no clue what is wrong, and you didn't tell us. What have you tried so far? Did it ever work?

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.

cloud dawn
#

Message content is since 2023 a privileged intent.

copper gulch
#

is asking help about a anti-nuke/anti-raid bot allowed here? or do I just have to figure it out on my own

#

cause like I was suppose to ask is there a way we can see who invited a certain bot and then get the id of that user and ban it and then include the bot that was invited aswell... It will start this action when channels getting deleted instantly and users getting banned continously... like about every less than a second

shrewd fjord
#

discord.on_integration_create

#

!d discord.on_integration_create

unkempt canyonBOT
#

discord.on_integration_create(integration)```
Called when an integration is created.

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

New in version 2.0.
copper gulch
shrewd fjord
#

this way you will know who and what bot they have added

copper gulch
shrewd fjord
#

and if you talk about how to nuke a server thenn... 💀

copper gulch
copper gulch
slate swan
shrewd fjord
copper gulch
#

Can a bot be triggered by a message that is sent by other bots? Or it only works with users?

shrewd fjord
#

no matter if its a user or bot account

copper gulch
#

Sooooo In python I guess I can make the bot trigger kick if a message is sent 10x in a second

shrewd fjord
#

yeah sure

livid juniper
#

simple roblox code whit slash command?

shrewd fjord
#

?

fading granite
#

is the current discord py supporting slash commands? i'm trying to use it but it says cannot import app_commands from discord

tall temple
#

please can someone help me to correct this import error ?

slate swan
#

what are you trying to do?

tall temple
#

for a specific slash cmd @default_permissions(administrator = True)

slate swan
#

!d discord.app_commands.default_permissions

unkempt canyonBOT
#

@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.

When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.

Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.

This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check). Therefore, error handlers are not called.

Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
tall temple
#

it's working in my other pc but in this one ...

#

idk why

slate swan
#

just shown you why

tall temple
#

kkk

slate swan
#

you did from discord import default_permissions

tall temple
#

yeah

slate swan
tall temple
#

pycord dude

slate swan
#

when did you tell me that?

tall temple
#

i didn't

slate swan
#

i even linked you discordpy docs and didnt tell anything

#

i doubt pycord has default_permissions as decorator

tall temple
slate swan
#

well it. does

tall temple
#

thx

slate swan
#

if you cant import it

#

means you are not using pycord

#

at least the import discord doesnt actually import pycord

#

maybe you installed other discord library

tall temple
#

yeah i always make this error CryptoMusique

#

i install pycord instead of py-cord

normal lava
#

Any one want to collab with me to create a project in py

cloud dawn
turbid condor
wicked atlas
#

Wait, this isn’t the Rust server?

hazy dune
#

How can I get the ID of the user, who used a slash command during the on_reaction_add event to the response of the command?

turbid condor
#

!d discord.on_reaction_add

unkempt canyonBOT
#

discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message_edit), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add) instead.

Note

To get the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Reaction.message).

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

Note

This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add) if you need this and do not otherwise want to enable the members intent.
hazy dune
#

yeah, I found that - I mean the author of the slash command, that the reaction was to

#

Ok, got through the docs... it's:

reaction.message.interaction.user.id
slate swan
warped mirage
maiden fable
warped mirage
slate swan
glad cradle
#

you need to have git installed

slate swan
glad cradle
#

btw d.py 2.0 is on pypi

glad cradle
slate swan
#

cause first answer he got was wrong

glad cradle
#

ah

slate swan
#

but yeah any of those commands will install you the latest discord.py @warped mirage

warped mirage
#

Alright. Thanks

void mauve
slate swan
#

it printed out when you clicked the button yeah?

void mauve
#

ye

slate swan
#

but it does not send this message await interaction.response.send_message('Bot is successfully configured.', ephemeral=True)

void mauve
#

no, it didn't

#

it just gives out "interaction failed"

#

and thats it

hushed galleon
#

could it have timed out?

#

creating that channel might have taken too long

slate swan
#

you maybe have error handler registered?

void mauve
slate swan
void mauve
hushed galleon
#

only the view error handler can do that, which they havent overridden

void mauve
#

is it mentioned in the docs?

slate swan
hushed galleon
#

oh wait, the default behaviour is to use the library logger rather than printing directly

#

in which case it can be suppressed if you didnt use Bot.run() or discord.utils.setup_logging()

slate swan
#

yeah set up logging

hushed galleon
void mauve
#

oh i see, i'll try that, thanks guys

glacial bison
#

i dont know how ro explain my problem but im trying to call a variable in the middle of text

slate swan
glacial bison
#

if message_content == "/pygmy rps":
import random
rpschoice = ["rock","paper","scissors"]
rps = random.randint(0,2)

    await message.channel.send("pick your choice")
    await message.channel.send('/spoiler'(rpschoice[rps]))
#

this is the code i have now, it works up until the point where it sends the second message

#

its supposed to send a spoiler message with either rock paper or scissors but it doesnt

slate swan
#

are you trying to make slash commands? or you just choose / to be prefix

glacial bison
slate swan
#

i would advise you to check out Bot class and how to create commands with it

#

instead of having it in on_message event

#

it would make it easier to accept arguments and stuff

final iron
cold sonnet
#

no way pep 8 compliance officer back at it

final iron
final iron
cold sonnet
#

no way

glacial bison
final iron
cold sonnet
#

that seems like a felony 💪

final iron
#

Also, settings "/" as your "prefix" is toture for the user as slash commands will come up each time they use the command

glacial bison
#

its working fine for us, sorry if it bothers you but i got it working perfecly fine for me

final iron
#

It doesn't bother me

cold sonnet
#

if it's working don't touch it

#

rule 1

final iron
#

It's just an outdated way of doing it

#

And you'll be missing out on a lot of features

slate swan
final iron
#

I think they're just new to all this

#

They'll come around eventually and fix it

#

It's not really possible to do what they're doing on a large scale lol

glacial bison
#

i dont see the issue, its working fine and if i need it to do something it cant do, ill fix it. its working fine, its not hurting me or you, so i dont understand the problem

final iron
#

Alright, when you come around though there are some good examples in the docs

#

Example of a basic bot to get you started

#

They also have them for modals, slash commands etc

glacial bison
#

ok

final iron
#

Is it possible to change your autocomplete suggestions depending on the input from a previous parameter?

slate swan
unkempt canyonBOT
#

The resolved namespace for this interaction.

If the interaction is not an application command related interaction or the client does not have a tree attached to it then this returns an empty namespace.

upbeat prawn
#

I'm using python 3.11, I want install discord-components, help. I'm getting an error. I know it works for older versions, but I want it to be 3.11

cloud dawn
hushed galleon
#

^

upbeat prawn
hushed galleon
#

slash commands and message components, albeit with no official guide on using them (just API reference and some examples)

halcyon acorn
#

from discord_slash import SlashCommand

Its saying this is not resolved when it is all installed.

final iron
#

Its outdated

#

!d discord.Invite.uses

unkempt canyonBOT
final iron
#

Not sure if it's possible to see who used it though

dry sedge
#

Is it possible to make something that makes it so the bot accepts a stage request to speak

final iron
#

!d discord.StageChannel

unkempt canyonBOT
#

class discord.StageChannel```
Represents a Discord guild stage channel.

New in version 1.7.

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.
hushed galleon
#

!d discord.Member.request_to_speak < never tried it, but i guess its possible

unkempt canyonBOT
#

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

Request to speak in the connected channel.

Only applies to stage channels.

Note

Requesting members that are not the client is equivalent to [`edit`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit) providing `suppress` as `False`.

New in version 1.7.
final iron
#

Oh yeah seems like it would work

winter token
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the 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.

mint forum
#

hi im looking for a script to keep my bot online 24/7, im usin visual studio code if that helps

final iron
#

If you're local hosting just run the file and don't stop it

mint forum
#

sorry not script id meant code

#

ah so all 24/7 hosting is a file?

final iron
#

I'm confused on what you mean

mint forum
#

yk

final iron
#

Do you already have a bot coded?

mint forum
#

slightly yes, not fully done, but id like it active without my comp needing to be on 24/7

final iron
#

Then you need a hosting service

#

AWS is a good option

#

Oracle as well

mint forum
#

Ok thanks

swift pumice
#

💯

normal lava
#

Can anyone want to collab with me I am going to create a economy bot

vale wing
#

I already stole all potential collaborators

#

Bobux bot is da greatest weary_lemon

hallow fog
#
    
    valid_chars = set("0123456789+-*/")
    
    
    in_number = False
    last_char = None
    has_operator = False
    
    for char in s:
        if char in valid_chars:
            if char.isdigit():
                if char == '0' and not in_number:
                    return False  
                in_number = True
            else:
                if not in_number:
                    return False  
                if has_operator:
                    return False  
                in_number = False
                has_operator = True
            last_char = char
        else:
            return False  
    
    if in_number:
        if last_char == '0':
            return False  
        return True  
    
    return has_operator  

user_input = input("Enter a string: ")


result = is_valid_expression(user_input)


print(result)```
#

someone help debug this pls

gloomy dune
#

this embed so messy how can ı fix it

#
    async def callback(self, interaction: discord.Interaction):
        new_embed = discord.Embed(title=f"{self.user.name} tarafından Pişirilenler", description="sex bunu nasıl dizayn edeceğime dair hiçbir fikrim yok.", color=discord.Color.dark_orange())
        new_embed.add_field(name="random number", value=f"random number: {random.randint(1, 10)}")
        new_embed.add_field(name="a", value="a 2")
        new_embed.add_field(name="b", value="b 3")
        new_embed.add_field(name="c", value="c 4")
        new_embed.add_field(name="d", value="d 5")
        
        await interaction.response.edit_message(embed=new_embed)
#

I want them in order from top to bottom

slate swan
#

!d discord.Embed.add_field

unkempt canyonBOT
#

add_field(*, name, value, inline=True)```
Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
slate swan
#

inline (bool) – Whether the field should be displayed inline.

unkempt canyonBOT
#

A module for evaluating math expressions without eval()

covert galleon
#

hello i need a Giveaway bot

#

link github

#

slach command

turbid condor
#

Go search it yourself

void mauve
#

How do I pin modal to a button?

import discord
import asyncio
import traceback

from discord import app_commands
from discord.ext import commands
from datetime import datetime

from funcs import func
from config import config


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)


class BotClient(commands.Bot):

    def __init__(self):
        intents = discord.Intents.all()
        intents.message_content = True

        super().__init__(command_prefix=commands.when_mentioned_or('.'), intents=intents)

    async def setup_hook(self) -> None:
        self.add_view(PersistentView)

    async def on_ready(self):
        func.console(f'Logged in as {self.user}. ID: {self.user.id}')


class Ticket(discord.ui.Modal, title='Ticket'):

    name = discord.ui.TextInput(
        label='Name',
        placeholder='Your name here'
    )

    ticket = discord.ui.TextInput(
        label='Your ticket',
        style=discord.TextStyle.long,
        placeholder='Type your ticket here',
        required=False,
        max_length=300
    )

    def __init__(self):
        super().__init__()
        self.ticket = ticket

    async def on_submit(self, interaction: discord.Interaction):
        print(self.ticket)

        message = discord.Embed(title=f"Thanks for submitting, {self.name}!",
                                description='Your ticket will be checked as soon as any staff member is available!',
                                colour=config.embed_color,
                                timestamp=datetime.now())

        await interaction.response.send_message(embed=message,
                                                ephemeral=True)

    # Error traceback
    async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
        await interaction.response.send_message(f'Oops! Something went wrong.', ephemeral=True)

        traceback.print_exception(type(error), error, error.__traceback__)


client = BotClient()


@client.command()
@commands.is_owner()
async def ticket(ctx: commands.Context):
    modal = Ticket()
    view = PersistentView()
    view.add_item(modal)
    await ctx.send(view=view)


client.run(config.token)
harsh orbit
#

How I can get command channel id

naive briar
#

What's command channel id

void mauve
# harsh orbit How I can get command channel id

if you need to find channel id by its name and category, you can use your own fucntion, like this:

async def find_channel_id(guild, channel_name, category_name):
    for category in guild.categories:
        if category.name == category_name:
            for channel in category.channels:
                if channel.name == channel_name and channel.guild == guild:
                    return channel.id
harsh orbit
naive briar
harsh orbit
naive briar
#

!d discord.ext.commands.Context.guild

unkempt canyonBOT
naive briar
unkempt canyonBOT
harsh orbit
#

Not guuld

#

The channel

naive briar
#

I'm dumb

#

!d discord.ext.commands.Context.channel

unkempt canyonBOT
naive briar
#

Just get the id attribute from it

harsh orbit
#

Id= discord.ext.commands.Context.channel
Print(Id)
It will print the id?

naive briar
#

No

#

You need a discord.ext.commands.Context instance

void mauve
harsh orbit
#

Ctx.command.Context.channel?

naive briar
#

No

#

If you have a context, then it's just ctx.channel.id

harsh orbit
#

Ok

naive briar
crimson hare
#

Hello, i'm searching help since morning to a basic question. I've an error in using channel.purge in an interaction command. Majority of purge command's exemple use ctx and it's working. I want still using interaction argument but without error.
My code :

@self.bot.tree.command(name="clear")
async def clear(interaction: ds.Interaction, number: int):
    author : ds.Member = interaction.user
    if author.guild_permissions.manage_messages:
        await interaction.channel.purge(limit=number)
        await interaction.response.send_message("End")
    else:
        await interaction.response.send_message("No perm required")
naive briar
naive briar
#

It would be useful, yes

crimson hare
#

Error :

Traceback (most recent call last):
  File "C:\Users\Me\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\...\Commands\PrivateCommand.py", line 13, in clear
    await interaction.response.send_message("nique ta grand mère le bot de tes morts (par Glerious)")
  File "C:\Users\Me\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 801, in send_message
    await adapter.create_interaction_response(
  File "C:\Users\Me\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

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

Traceback (most recent call last):
  File "C:\Users\Me\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\Me\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Me\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'clear' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
#

I didnt filter it, I didn't understoud a lot

naive briar
#

You didn't respond in time (3 seconds), try to defer the interaction before calling the purge method and send a follow-up after the purge

#

!d discord.InteractionResponse.defer - use this to defer

unkempt canyonBOT
#

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

Defers the interaction response.

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

This is only supported with the following interaction types...
naive briar
#

!d discord.Interaction.followup - then use this to send a follow-up

unkempt canyonBOT
crimson hare
#

ok thanks

crimson hare
crimson hare
#
Traceback (most recent call last):
  File "C:\Users\Me\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\...\Commands\PrivateCommand.py", line 14, in clear
    await interaction.followup.send("End")
  File "C:\Users\Me\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 1805, in send
    data = await adapter.execute_webhook(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Me\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message

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

Traceback (most recent call last):
  File "C:\Users\Me\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\Me\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Me\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'clear' raised an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message
naive briar
#

Well, I guess it's true then

naive briar
#

You might want something else like interaction.channel.send instead to get rid of the error

#

!d discord.Interaction.channel

unkempt canyonBOT
crimson hare
#

ok nop, don't delete it

#

Ok it's good and thanks

harsh orbit
#

If I made a @has_role()
So what is the name of the error of hot doesn't have a role?

#

MissingRole?

void mauve
naive briar
void mauve
#

thanks, im just blind hmm

shrewd apex
#

it inherits from CheckFailure iirc

harsh orbit
#

Ok thx

smoky anvil
#

How do i make a giveaway with countdown as timestamp?

slate swan
#

You can make timestamp with R flag which standa for relative

#

Something Like <t:YOUR_TIMESTAMP:R>

south aurora
#

AttributeError: module 'tasks' has no attribute 'loop'

i cant figure this out please help

smoky anvil
shrewd apex
#

u can use it anywhere

smoky anvil
#

hmm

#

thanks!

#

but how can i turn into a coundown / ends message in giveaway embed?

slate swan
#

!d discord.utils.format_dt

unkempt canyonBOT
#

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

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

And the library/version you're trying to use

harsh orbit
#

How I can make my bot check the channel name start because I want I command doesn't work except in a channel start with a specific word

south aurora
harsh orbit
#

My English is bad 😅

unkempt canyonBOT
#

str.startswith(prefix[, start[, end]])```
Return `True` if string starts with the *prefix*, otherwise return `False`. *prefix* can also be a tuple of prefixes to look for. With optional *start*, test string beginning at that position. With optional *end*, stop comparing string at that position.
slate swan
unkempt canyonBOT
harsh orbit
slate swan
#

!e ```py
string = "something"
print(string.startswith("some")) # True

unkempt canyonBOT
#

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

True
harsh orbit
#

Wait I will try something

slate swan
#

!d discord.ext.commands.Context

unkempt canyonBOT
#
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable) ABC.
slate swan
#

check docs Shrugdge

harsh orbit
#

Please nooo

#

I tired

gilded nimbus
#

anyone onlin

#

need some help

slate swan
#

you need to run it on class instnace

#

!d discord.ext.commands.Context.channel like this

harsh orbit
#

Ok

unkempt canyonBOT
slate swan
#

if you got ctx

gilded nimbus
#

I have a chatbot in python and i want to use it on my HTML page front end. How can i send a prompt from my front end to the chat bot?

smoky anvil
#

?

slate swan
#

actually just

#

on each button click increment the button label number by one

#

literally what you are looking for^

smoky anvil
#

thanks!

slate swan
#

but it just counts to 5

smoky anvil
#

oo but that is something you can change?

slate swan
#

and accepts many clicks you need to check if user is already registered

slate swan
#

see the code play with it and you will eventually understnad it

smoky anvil
#

o i see, thanks a lot man!

#

the problem with that is you cant see the participants

dense coral
#
async def setup():
    await bot.wait_until_ready()
    async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:
            await cursor.execute("CREATE TABLE IF NOT EXISTS totals (guild_id int, inviter_id int, normal int, left int, fake int, bonus int, PRIMARY KEY (guild_id, inviter_id))")
            await asyncio.sleep(1)
            for guild in bot.guilds:
                for invite in await guild.invites():
                    await cursor.execute("INSERT OR IGNORE INTO invites (guild_id, invite_id, uses) VALUES (?,?,?)", (invite.guild.id, invite.id, invite.uses))
                    await cursor.execute("INSERT OR IGNORE INTO totals (guild_id, inviter_id, normal, left, fake, bonus) VALUES (?,?,?,?,?,?)", (guild.id, invite.inviter.id, 0, 0, 0, 0))
        await db.commit()

bot.loop.create_task(setup())```
I have a Task TimeoutError
harsh orbit
#

@bot.command()
@has_role("Support")
async def come(ctx, member: discord.Member):
  roomname = ctx.channel.name
  check = string.startswith("ticket")
  print(check)
  if check == True:
      ticket = f"<#{ctx.channel.id}>"
      comer = f"<@{ctx.author.id}>"
      mention = member.mention
      await member.send(f"**SwesRa Host**\n {ticket} تم استدعائك في التكت\n يرجى القدوم لتفادي اغلاق التكت \n \nاستدعيت بواسطة: {comer}\n\n {mention}")
      await ctx.reply(member.mention + " Has been called")

  else:
      ctx.reply("This command only work in ticket ")

@come.error
async def come_error(ctx, error):
   if isinstance(error, commands.MissingRole):
     await ctx.reply("** Only Support team can use the command**")

   elif isinstance(error, commands.MissingRequiredArgument) or (error, commands.BadArgument):
     await ctx.reply("Please use the command in the correct way \n `,come (member)`")

Why when I added the if and else and run the command it telling me it's missing argument or bad argument?

#

I know there is a mistake

#

But what the link of bad argument with it?

hushed galleon
#
isinstance(error, commands.MissingRequiredArgument) or (error, commands.BadArgument)``` this will always evaluate to true because `(error, commands.BadArgument)` is merely a non-empty tuple - the way you should check for multiple types with isinstance is passing a tuple of types to the function, i.e. ```py
isinstance(error, (commands.MissingRequiredArgument, commands.BadArgument))```
harsh orbit
#

Why this thing ain't happening before I add the if and else?

hushed galleon
#

shrug, perhaps your command is raising an error but your error handler is incorrectly telling you that you mistyped your argument (error handlers are more complex than you'd think from the discord.py docs, so its very easy to screw up)

#

check = string.startswith("ticket") is referring to a string variable that isnt defined in your example

harsh orbit
#

It's now
roomname.startwith....

#

Wait

hushed galleon
dense coral
#

of course

Task exception was never retrieved
future: <Task finished name='Task-1' coro=<setup() done, defined at /home/container/main.py:5770> exception=TimeoutError()>
Traceback (most recent call last):
  File "/home/container/main.py", line 5780, in setup
    for invite in await guild.invites(): # invites before bot was added won't be recorded, invitemanager/tracker don't do this
                  ^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/nextcord/guild.py", line 2317, in invites
    data = await self._state.http.invites_from(self.id)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/nextcord/http.py", line 300, in request
    async with self.__session.request(method, url, **kwargs) as response:
  File "/home/container/.local/lib/python3.11/site-packages/aiohttp/client.py", line 1141, in __aenter__
    self._resp = await self._coro
                 ^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/aiohttp/client.py", line 467, in _request
    with timer:
  File "/home/container/.local/lib/python3.11/site-packages/aiohttp/helpers.py", line 721, in __exit__
    raise asyncio.TimeoutError from None
TimeoutError```
harsh orbit
#

The problem has been solved

#

Thx

dense coral
hushed galleon
hushed galleon
dense coral
hushed galleon
#

its a dependency of nextcord so you do have it, but judging from traceback/source code im guessing its v3.8.5

#

not sure why, but i guess your invites request timed out after 5 minutes?

dense coral
#

Since when is there a timeout for a task?

hushed galleon
#

its not the task itself timing out, its the HTTP request nextcord is making that's timing out

#

dunno why it is though

slate swan
#

I am about to rip every single strand of hair out.

I am relatively new to programming

I am working on a bot, but I am getting this error:
D:\BotForTesting\testrewrite.py:189: RuntimeWarning: coroutine 'initiateBot' was never awaited
initiateBot()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

Here is the code that it is referencing

async def initiateBot():
    global intents
    intents  = discord.Intents.all()
    global bot
    bot = commands.Bot(command_prefix='!', intents=intents)
    global client
    client = discord.Client(intents=intents)


@client.event
async def on_ready():
    await client.change_presence(activity=discord.Game(name="the world burn"), status=discord.Status.dnd)
    printorange("Bot is ready.")  
    finishedLoadingBot = True      

bot.run(---------there is a valid token here in my real script-----------') 

I cannot figure out the best way to have the bot start when I call the function "initiateBot()"

Could I get some help?

dense coral
cold sonnet
#

I don't like that

#

matter of fact I hate that

cold sonnet
#

initiateBot

#

can be replaced with a single line

hushed galleon
cold sonnet
#

you go gamecracks

slate swan
#

Making use of global is absolutely shit

dense coral
hushed galleon
#

i.e. ```py
bot = commands.Bot(...)

Events and commands here

bot.run(...)``` note that discord.Client and commands.Bot should not be mixed, anything you can do with a client works the same for the bot

slate swan
slate swan
#

!code

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.

slate swan
#

Read the embed duh

cold sonnet
#

that should be a thing

hushed galleon
#

oh in that case a function is fine, but trying to use globals will make it more complicated

cold sonnet
#

I mean !code code

slate swan
#

No, what should be a thing is people reading

cold sonnet
#

someone get that into the python bot

#

nah actually it's kinda fucking useless

slate swan
#

I figured it out

#

should i just put the code as the result and skip creating a function?

hushed galleon
#

the cheapest solution would be putting all of your bot definitions (events/commands included) inside the function, i.e. ```py
def run_bot():
bot = commands.Bot(...)

@bot.event
async def on_ready():
    ...

bot.run(...)

if user_input == "run bot":
run_bot()``` a cleaner approach would be subclassing the bot and using cogs/extensions

slate swan
#

Ok

#

thank you, my small brain would have taken years to come up with that

restive dagger
#

i have a problem

dense coral
restive dagger
#

I need a easy db easy to write and update that is easy and uses py

slate swan
#

SQLite, PostgreSQL, MongoDB, whatever else

restive dagger
#

ah

final iron
#

!rule 5

unkempt canyonBOT
#

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

final iron
robust fulcrum
normal lava
#

I made a economy bot

#

How I can i promote itpithink

final iron
#

It's so oversaturated

#

You could try getting the bot into a large server

#

Eventually it'll get to the point where it's exponential growth, but getting started is the hardest

slate swan
#

Someone dm me I got a project

shrewd apex
normal lava
#

I made some new features like investing @final iron

normal lava
shrewd apex
#

contact some big server owners flex your bot on them

#

also make sure ur bot requires minimal permissions

normal lava
#

Hn

#

Only send mssg

shrewd apex
#

cool

normal lava
#

Can u come and test pls @shrewd apex

shrewd apex
#

nah I'll pass i am busy

normal lava
#

Ohk

harsh orbit
#

There a bot in discord called probot it is have a currency called credit so there are some bots make auto sell like when someone transfer credit to the seller the bot send to him what he bought in dm
Anyone have an idea how to that like when someone transfer a specific amount of credit to someone there is action happen

naive briar
#

Check the amount and do the action? 🤷

def transfer(amount: int, ...):
    ...

    if amount >= 50000:
        print("50000!? O.o")

    ...
slate swan
#

Is there a global app commands error handler?

For ctx commands, it's:

@commands.Cog.listener()
async def on_command_error(ctx, error)```
but this doesn't work with app commands.
turbid condor
#

For app_commands you have handle the error by tree

slate swan
turbid condor
#

No i told u it's by tree

#

Like

#
tree = bot.tree #your defined tree

@tree.error()
async def on_app_command_error(interaction:discord.Interaction, error):
# rest is pretty similar to the on_command_error handler
#

Here is how to handle Tree/App command errors in a cog/extension.
There are 2 ways to do it.

Option 1: A global error handler for your CommandTree (all app commands). Like stated above.
Option 2: A special method that is called for slash command errors in this cog.

from discord import Interaction
from discord.app_commands import AppCommandError

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

    # -> Option 1 ---
    # attaching the handler when the cog is loaded
    # and storing the old handler
    # this is required for option 1
    def cog_load(self):
        tree = self.bot.tree
        self._old_tree_error = tree.on_error
        tree.on_error = self.on_app_command_error

    # -> Option 1 ---
    # detaching the handler when the cog is unloaded
    # this is optional for option 1
    def cog_unload(self):
        tree = self.bot.tree
        tree.on_error = self._old_tree_error

    # -> Option 1 ---
    # the global error handler for all app commands (slash & ctx menus)
    async def on_app_command_error(
        self,
        interaction: Interaction,
        error: AppCommandError
    ):
        print("This error was handled with option 1 from ?tag treeerrorcog")
          ...

    # -> Option 2 ---
    # the error handler for slash commands in this cog
    async def cog_app_command_error(
        self,
        interaction: Interaction,
        error: AppCommandError
    ):
        print("This error was handled with option 2 from ?tag treeerrorcog")
        ...

# add and load the cog like normal 
async def setup(...):
  ...
turbid condor
harsh orbit
#

It's not my bot

shrewd apex
# harsh orbit It's not my bot

u cant track transfers made in other bots unless the bot dev makes those transactions public by announcing in some channel or smn

harsh orbit
#

But I don't think that's the way

#

Because who made auto selling bot

#

Only gets the Id

#

So if there are no way to make this

#

How them do it?

#

I can show you a bot that's make this thing

sharp whale
#

Error Traceback (most recent call last): File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 827, in _do_call return await self._callback(self.binding, interaction, **params) # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "e:\honey\Programming\Fiverr\Making\ohhsodead's order\cogs\search.py", line 90, in search_playstation await pages.start(interaction) File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\dispie\paginator\__init__.py", line 144, in start self.message = await self.interaction.followup.send(**kwargs, view=self) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: discord.webhook.async_.Webhook.send() got multiple values for keyword argument 'view'

#

!paste

shrewd apex
sharp whale
naive briar
#

Why?

harsh orbit
sharp whale
naive briar
#

Errors don't lie

#

Except if someone made it to

sharp whale
#

I sent the code

shrewd apex
shrewd apex
#

pretty sure what you are trying is against tos

harsh orbit
#

Can I show a bot that make this thing

#

Because you didn't understand

naive briar
shrewd apex
#

then explain here in detail so everyone can understand

sharp whale
naive briar
#

!pypi dispie

unkempt canyonBOT
harsh orbit
# shrewd apex then explain here in detail so everyone can understand

There is a discord bot have a currency called credits and there is a command to transfer them to another one or account
There are bots auto selling things with credit like someone use command $buy the bot reply to him please transfer that's amount of credits and when he transfer them the bot do an action like send what he bot in his dm
And if the buieer transfered a wrong amount or for different account the bot not doing anything
The selling bot don't get any information exept the account id and probot id

#

Hope you understand

unkempt canyonBOT
#

dispie/paginator/__init__.py line 90

kwargs = {"content": None, "embeds": [], "view": self}```
`dispie/paginator/__init__.py` line 144
```py
self.message = await self.interaction.followup.send(**kwargs, view=self)```
naive briar
#

They explicitly give the function two view keyword arguments

sharp whale
#

ahh what

harsh orbit
naive briar
sharp whale
#

ahhh

harsh orbit
#

No one knows 😒

naive briar
#

Know what?

sharp whale
shrewd apex
# harsh orbit .

so what do u want know? how bot detects transaction is completed?

naive briar
shrewd apex
naive briar
shrewd apex
#

its not that hard

sharp whale
#

hmm

shrewd apex
# harsh orbit Yup

how do users transfer via button or command if it were me i would use a view component callback

sharp whale
shrewd apex
#

dont think probot is open source is it?

#

so we can only assume

shrewd apex
#

example of?

unkempt canyonBOT
#

dispie/paginator/__init__.py line 90

kwargs = {"content": None, "embeds": [], "view": self}```
harsh orbit
shrewd apex
#

screen record a video ping me in ot

harsh orbit
#

Ok I will record a vid

shrewd apex
#

aight cool

harsh orbit
#

Wait

sharp whale
#

like, how do i do it

naive briar
#

Remove "view": self from kwargs variable definition ducky_wizard

harsh orbit
naive briar
naive briar
#

I guess the second option is safer

naive briar
harsh orbit
shrewd apex
# harsh orbit <@656838010532265994>

its using some credit id it could be a transaction id i am not really sure whats happening here i can see a bunch of payment options on ur bot where u clicked probot and then revealed a id thats it i am a bit lost sorry

sharp whale
#

you started typing as i sent the message

#

fast af boi

shrewd apex
#

nope i am kinda lost in context of the situation

naive briar
#

That really makes me want to just quit

shrewd apex
harsh orbit
shrewd apex
#

try in some other channel perhaps

sharp whale
harsh orbit
#

I think this thing hard in discord.py because this bots are made in js

shrewd apex
harsh orbit
#

And every J's programmer see this thing easy

unkempt canyonBOT
#

@shrewd apex :white_check_mark: Your 3.11 eval job has completed with return code 0.

bar
naive briar
shrewd apex
harsh orbit
naive briar
shrewd apex
#

i so far dont even know what the thing is thats your ultimate goal

harsh orbit
#

Program an auto sell bot

naive briar
#

Sell what now?

sick birch
shrewd apex
#

so why does probot come in picture

harsh orbit
shrewd apex
#

and verifying payment using discord bots sounds more pain than worth it tbh use a website

harsh orbit
shrewd apex
#

or dashboard for that

#

u cant trade probot or bot currency for irl cash

#

its against tos of discord

naive briar
#

Doesn't sound suspicious at all 🤭

harsh orbit
shrewd apex
#

so ur trying to verify wether probot currency has been transferred to another user?

harsh orbit
#

Yup

harsh orbit
#

For spesfic user and spesfic amount

shrewd apex
#

does probot reveal any of this information?

harsh orbit
#

Nope

#

But there tooooooooo many auto sell bots

naive briar
#

Ah, yes

shrewd apex
#

if it dosent reveal the information then its probably not something we can help u make without jumping on grey borders

harsh orbit
sharp whale
#

its a complete different thing

naive briar
#

But exactly the same concept

sharp whale
#

uhh

shrewd apex
#

i am gonna go get some snacks

slate swan
harsh orbit
#

Np

sharp whale
#

DOWNNN

#

@slate swan ayo can you help me

slate swan
#

if you send your question i can think about it

sharp whale
#

Error

  File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 827, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "e:\honey\Programming\Fiverr\Making\ohhsodead's order\cogs\search.py", line 93, in search_playstation
    pages = Paginator(embeds,
            ^^^^^^^^^^^^^^^^^
TypeError: Paginator.__init__() got an unexpected keyword argument 'view'

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

Traceback (most recent call last):
  File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'search_playstation' raised an exception: TypeError: Paginator.__init__() got an unexpected keyword argument 'view'```
slate swan
#

and code?

sharp whale
#

code

shrewd apex
#

its library issue

naive briar
#

lol

slate swan
slate swan
sharp whale
slate swan
sharp whale
#

I searched in that code, I have the same thing as that code

naive briar
#

Interesting how the sticker has a server's link ducky_sus

shrewd fjord
#

it doesnt work i think FR_sus but lemme delete it anyway

slate swan
naive briar
#

Eh, I don't think they'd kill you because of it

shrewd fjord
#

thanks for saving sleeping_cat_hehe

sharp whale
#

._.,

shrewd fjord
#

.-.

slate swan
#

:l

sick birch
shrewd fjord
slate swan
slate swan
cloud dawn
#

!e ```py
from datetime import datetime

dt = datetime(1960, 1, 1)
print(dt)

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.

1960-01-01 00:00:00
restive dagger
#

I need a free discord bot hosting

restive dagger
#

Well is there a free one???

cloud dawn
slate swan
#

cause why would somebody want to host something for free since its using resources

tardy pecan
#

Hey whats the way to add_reaction on bots message (which bots send just now)

I try to used

await message.client.add_reaction(💔)

it's not working

slate swan
#

!d discord.Message.add_reaction

unkempt canyonBOT
#

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

Adds a reaction to the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji).

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) to do this. If nobody else has reacted to the message using this emoji, [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions) is required.

Changed in version 2.0: `emoji` parameter is now positional-only.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) instead of `InvalidArgument`.
slate swan
#

when you send a message assign it to a varriable

#

then use this method on it

buoyant quail
#

(It's Message method, not Client method)

dapper cobalt
#
def infractionable():
    async def predicate(ctx: Context, user: discord.User):
        is_highrank = ctx.author.top_role < user.top_role
        is_owner = user == ctx.guild.owner
        is_bot = user == ctx.bot
        
        if any([is_highrank, is_owner, is_bot]):
            return False
        else:
            return True
        
    return check(predicate)

apparently this doesn't work since user needs to be passed in the decorator, so how can i get the user passed in the command's kwargs?

buoyant quail
#

And what is that user? (sorry i didn't read xd)
An argument? Then you want a converter i think, not a check

slate swan
timid spade
#

any advice how should i store data if bot is in multiple servers? data like welcome messages for each server and welcome messages channel, admin roles etc
i am using sql rn but should i shift to json? i usually see json data everywhere

thin raft
#

use a postgre or mongo

slate swan
#

dont use .json files for sure

#

mongo uses json format to store data

timid spade
#

okay i see, mongo or postgre
not even sql?

slate swan
#

sql is fine too

timid spade
#

okay

random zephyr
#

i need help

#

im making a discord bot

#

and whenever i paste the premade script on python 3

#

it keeps on failing and executing the wrong stuff

slate swan
#

That's unfortunate

glad cradle
formal basin
slate swan
#

That's also a reason why you should learn and write your own code instead of copy pasting 👍

slate swan
#

just notepad

glad cradle
#

that's why they're convenient

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

slate swan
#

Learn python, at least the basics, and then come back

#

To make a discord bot you should have an advanced knowledge of the language

mighty pilot
#

If people did that, this channel wouldn't exist

random zephyr
#

is there any other txt file i can use

mighty pilot
harsh orbit
#
@bot.command(aliases=["خط"])
@has_permissions(administrator=True)
async def line(ctx, id=None):
  line = "https://cdn.discordapp.com/attachments/1135214502502207678/1140945475520954429/line.png"
  if id == None:
      await ctx.message.delete()
      await ctx.send(str(line))
  else:
    channel = bot.get_channel(id)
    await channel.send(line)

Why when I put a channel id after ,line nothing happen?

buoyant quail
#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
harsh orbit
#

So?

buoyant quail
#

Parameters
id (int) – The ID to search for.

slate swan
#

you are receiving str

buoyant quail
#

It accepts only integers, not strings

slate swan
#

annotate id as int

harsh orbit
#

Just I add
int(id)?

buoyant quail
#

As an option

#

Annotating it would be better

harsh orbit
#

Wdym by annotating

slate swan
#
def function(argument: int):
    ...
#

argument is annotated to be int

#

also dont name your varriable the same as function name

harsh orbit
#
@bot.command(aliases=["خط"])
@has_permissions(administrator=True)
async def line(ctx, id=None):
  line = "https://cdn.discordapp.com/attachments/1135214502502207678/1140945475520954429/line.png"
  if id == None:
      await ctx.message.delete()
      await ctx.send(str(line))
  else:
    channel = bot.get_channel(int(id)) 
    await channel.send(line)

Still not working
Note: there are no error happened

slate swan
#

you have any error handler?

harsh orbit
#

No errors

#

Just nothing happens

#

,line 1130900936198475856
That's the command

slate swan
#

Intent enabled?

harsh orbit
#

Yup

buoyant quail
harsh orbit
#

I thing I made i mistake in if and elae

harsh orbit
buoyant quail
#

Issue is somewhere else. Not in that part of code

slate swan
harsh orbit
#

Wait

#
@line.error
async def line_error(ctx, error):
   if isinstance(error, commands.MissingPermissions):
     await ctx.reply("**You don't Have permissions to use this command**")

You mean this?

slate swan
#

yes

#

what if the error that happens will be other than MissingPermissions

#

it will just be thrown away so you are silencing your errors

#

add else and print or reraise the exception

harsh orbit
#

Bro

#

I asking why the command not working

slate swan
#

...

harsh orbit
#

I know it's not fully organized

slate swan
#

we are about to find out?

buoyant quail
#

Because you are actually getting an error, but it's hidden by your handler

slate swan
#

we would know why its not working if we had error

buoyant quail
#

Which does absolutely nothing when you get some error except missing permissions

slate swan
#

but your error handler hides it

#

does that make sense why we are working on error handler now?

harsh orbit
#

Wait I think it's worked

slate swan
#

bro you even read my messages

slate swan
#

every

#

can you do what i said about the handler

harsh orbit
#

The command worked actually

#

No need to add print

harsh orbit
#

I now just make some tests it's not completed command

sharp whale
#

:)

harsh orbit
#

Can anyone give a doc or something to learn how to make my bot make and edit channels?

cloud dawn
unkempt canyonBOT
#
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

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

Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels) to create the channel.

The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite) as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit) will be required to update the position of the channel in the channel list...
cloud dawn
#

This includes everything.

harsh orbit
#

I want edit permissions

#

And add roles and edit their permissions in room

final iron
unkempt canyonBOT
#

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

Edits the role.

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

All fields are optional.

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

Changed in version 2.0: Edits are no longer in-place, the newly edited role is returned instead...
harsh orbit
final iron
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.
harsh orbit
#

I want to edit role in room

final iron
#

wdym room

harsh orbit
#

Channel

final iron
#

I don't understand what you mean

#

You want to edit the roles in a channel?

harsh orbit
#

._.

final iron
#

How about you actually try explaining

harsh orbit
#

..

#

Anyone here?

#

@final iron

final iron
harsh orbit
harsh orbit
#

Nice helpers 🙂

final iron
#

I still have no clue what you're asking

harsh orbit
#

I will record a vid

wicked atlas
#

!d discord.abc.GuildChannel.set_permissions

unkempt canyonBOT
#

await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sets the channel specific permission overwrites for a target in the channel.

The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role) that belongs to guild.

The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions) attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.

If the `overwrite` parameter is `None`, then the permission overwrites are deleted.

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

Thisssss

wicked atlas
#

this should be a method of any channel object you get with discord.py

#

unless it's a dm

harsh orbit
#

Can you give me a docs?

wicked atlas
#

click the link in the title of the embed, it should take you right to it

harsh orbit
#

Ok thx

final iron
#

absolute monstrosity

#

I was on some shit when I wrote that ngl

sick birch
#

🥴

#

I used to write code like that

final iron
#

I was tired

sick birch
#

At least I'm better now

final iron
#

why tf did I convert that to a string and then convert to a float

final iron
#

It's getting out of hand

#

There's just so many different inputs I have to account for, so sometimes I have to

sick birch
#

the common wisdom there is usually to simply not account for them

#

don't pollute your codebase trying to accept a variety of argument types

harsh orbit
#
await message.channel.set_permissions(message.author, read_messages=True,
                                                      send_messages=False)

This code for author how I can make it for a specific role?

#

Or everyone role

#

@sick birch

upbeat gust
#

!d discord.Guild.get_role

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID.

Changed in version 2.0: `role_id` parameter is now positional-only.
upbeat gust
unkempt canyonBOT
harsh orbit
#

Ok thx

harsh orbit
harsh orbit
upbeat gust
harsh orbit
#
if overwrite.view_channel == False:
    ctx.reply("this channel is already hidden")

How is the right way to do this

#

overwrite = discord.PermissionOverwrite()

#

I mean

#

How to check if a permission true or false?

upbeat gust
harsh orbit
#

A role in a room

#

Like everyone role in owners room view_channel = false

#

So how I can make my bot check for this?

#

I mean channel by room

upbeat gust
#

1 sec

harsh orbit
#

Ok

upbeat gust
#

!d discord.TextChannel.permissions_for

unkempt canyonBOT
#

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

This function takes into consideration the following cases...
upbeat gust
#

you can use this like

harsh orbit
#

Example pls

upbeat gust
#

if channel.permissions_for(role).send_messages:

harsh orbit
#

Thx a lot

slate swan
#

make bot en ligne

obsidian fable
#

how do I call this type of interaction?

fading marlin
#

A Modal

#

!d discord.ui.Modal

unkempt canyonBOT
#

class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.

This object must be inherited to create a modal popup window within discord.

New in version 2.0.

Examples...
obsidian fable
#

thank you!

fading marlin
#

Sure thing

upbeat gust
slate swan
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the 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.

final iron
#

with what

#

how about you actually be descriptive with whatever you want

slate swan
#

Keep getting that error

final iron
#

I'm not going to play 21 questions

#

Actually be descriptive

slate swan
#

No idea, that’s the error I’m getting from the code 😭

#

When I run the command I get the error

final iron
#

read the traceback

slate swan
#

Don’t get a traceback

final iron
#

Remove your error handlers

final iron
#

Yes, remove your error handlers

slate swan
# final iron Yes, remove your error handlers

Traceback (most recent call last):
File "C:\Users\chain\Downloads\Recover_Cord_1\Recover_Cord_1\Recover_Cord (1)\Recover Cord\PRIVATE BOTS\Refactor\Server Backup\commands\backup.py", line 88, in backup
async for message in channel.history():
File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\iterators.py", line 123, in anext
return await self.next()
^^^^^^^^^^^^^^^^^
File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\iterators.py", line 325, in next
await self.fill_messages()
File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\iterators.py", line 348, in fill_messages
data = await self._retrieve_messages(self.retrieve)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\iterators.py", line 370, in _retrieve_messages_before_strategy
data: list[MessagePayload] = await self.logs_from(
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 367, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10003): Unknown Channel

final iron
#

Okay so, async for message in channel.history(): is your issue

#

Also don't use json as a database

slate swan
final iron
#

Still

#

SQL is literally easier

#

ngl its hella unreadable

slate swan
#

Fixed my error

final iron
#

What was it?

slate swan
#

One of my channels was inaccessible, so i made it skip over the channels that are inaccessible

final iron
#

Also this is going to ratelimit your bot insanely fast

slate swan
final iron
#

sure

slate swan
#

An error occurred: 'NoneType' object is not iterable

#

What causes that error

turbid condor
slate swan
#

I can do something like that?

turbid condor
#

What is text_channels and voice_channels in this case?

#

Cuz as far as i can see you have a channels variable

turbid condor
slate swan
turbid condor
#

Like if you are getting a channel

text= bot.get_channel(ID)
if text is None:
    print("Channel Not found")

Now if the bot is not able to find that channel it will trigger the if block.

slate swan
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the 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
#

@turbid condor I tried for almost 45 mins to fix it

naive briar
#

Fix what

slate swan
#

An error occurred: 'NoneType' object is not iterable

naive briar
#

!traceback

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

slate swan
naive briar
#

Then there's not enough information to identify where the error occurred 🤷

final iron
#

Remove your code that's doing it

slate swan
slate swan
final iron
#

Remove them and send the traceback

slate swan
final iron
slate swan
#

!pasted

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
#

i added a print function, but it sends to discord whyy

final iron
#
                except (discord.NotFound, AttributeError):
                    # Handle "Unknown Channel" error by skipping inaccessible channels
                    continue

🥶

final iron
#

tf u mean you removed it

slate swan
#

oops

final iron
#

It's still there

slate swan
#

wrong section hold on

final iron
#

You're killing me here

#

I'm tryna go to sleep

slate swan
#

boom

final iron
#

Okay so share the traceback now

#

user_avatars[message.author.id] = str(message.author.avatar.url) if message.author.avatar else None
😩

#

This vexes me

slate swan
#

it still sends to the bot on discord im literally confused

final iron
#

Did you restart the bot

slate swan
#

Yes

final iron
#

Change the token

#

There’s either a different instance running or there’s another error handler somewhere

#

If it stays after the token change you have another error handler

slate swan
#

now my slash commands arent there.

#

there has to be another one.

slate swan
# final iron There’s either a different instance running or there’s another error handler som...

Traceback (most recent call last):
File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "C:\Users\chain\Downloads\Recover_Cord_1\Recover_Cord_1\Recover_Cord (1)\Recover Cord\PRIVATE BOTS\Refactor\Server Backup\commands\setbackup.py", line 128, in on_application_command_error
raise error
File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'NoneType' object is not iterable

final iron
#

Like just read

#
on_application_command_error
    raise error
#

There's another error handler

slate swan
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the 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
#

all removed....

final iron
#

Is it the same file

slate swan
#
  File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
          ^^^^^^^^^^^^^^^
  File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 978, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "C:\Users\chain\Downloads\Recover_Cord_1\Recover_Cord_1\Recover_Cord (1)\Recover Cord\PRIVATE BOTS\Refactor\Server Backup\commands\restore.py", line 76, in restore
    for message in channel_messages:
TypeError: 'NoneType' object is not iterable

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

Traceback (most recent call last):
  File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\chain\Downloads\Recover_Cord_1\Recover_Cord_1\Recover_Cord (1)\Recover Cord\PRIVATE BOTS\Refactor\Server Backup\commands\setbackup.py", line 128, in on_application_command_error
    raise error
  File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'NoneType' object is not iterable```
final iron
#

Finally

#

channel_messages is None

#

That's in a different file or you're not sharing all the code

slate swan
harsh orbit
#

Can anyone just give me an idea to how to make a setup command like there are on member join and to select it channel you need to use a command like $set_greet (channel id) and this id will go into the event of on_member join

harsh orbit
#

...

vocal snow
#

Have you worked with any kind of persistent storage before

#

Files or databases

harsh orbit
#

No

#

That's why I'm asking you

harsh orbit
vocal snow
harsh orbit
#

And I have another question

#

How can I edit a message the bot has sent it before?

vocal snow
#

Store the message object returned by .send

#

Or it's id, then fetch the object with TextChannel.fetch_message later

harsh orbit
#

Can you give me an example?

vocal snow
#

msg = await messageable.send(...)
await msg.edit(...)

harsh orbit
#

How I can get message object by message Id?

#

bot.get_message()?

vocal snow
#

!d discord.TextChannel.fetch_message

unkempt canyonBOT
#

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

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) from the destination.
harsh orbit
#

Can you give example for code who edit a message have sent it before

high prairie
#

I am a senior python dev

somber sky
#
@client.tree.command(description='Get reaction roles.')
@app_commands.choices(role=[
  app_commands.Choice(name="Pickup Ping", value="Pickup Ping"),
  app_commands.Choice(name="Stream Ping", value="Stream Ping"),
  app_commands.Choice(name="Giveaway Ping", value="Giveaway Ping"),
  app_commands.Choice(name="Events Ping", value="Events Ping"),
  app_commands.Choice(name="Waitlist Ping", value="Waitlist Ping"),
  app_commands.Choice(name="Media Ping", value="Media Ping")
])
async def roles(i: discord.Interaction,
               role: app_commands.Choice[str]):
  PRole = discord.utils.get(i.guild.roles, name="Pickup Ping")
  SRole = discord.utils.get(i.guild.roles, name="Stream Ping")
  GRole = discord.utils.get(i.guild.roles, name="Giveaway Ping")
  ERole = discord.utils.get(i.guild.roles, name="Events Ping")
  WRole = discord.utils.get(i.guild.roles, name="Waitlist Ping")
  MRole = discord.utils.get(i.guild.roles, name ="Media Ping")

  if (role.value == 'Pickup Ping'):
    await i.user.add_roles(PRole)```

Making reaction roles with a selection menu, how do i make it where if you press the same role then it will remove it
harsh orbit
#

Can anyone give me the name of this 4 permissions in overwrits

slate swan
#

!d discord.Permissions

unkempt canyonBOT
#

class discord.Permissions(permissions=0, **kwargs)```
Wraps up the Discord permission value.

The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.

Changed in version 1.3: You can now use keyword arguments to initialize [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions) similar to [`update()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.update).
slate swan
#

you have list of attributes here

harsh orbit
#

Where is 3?

turbid condor
harsh orbit
#

..

slate swan
unkempt canyonBOT
#
Not likely.

No documentation found for the requested symbol.

slate swan
#

!d discord.abc.GuildChannel

unkempt canyonBOT
#

class discord.abc.GuildChannel```
An ABC that details the common operations on a Discord guild channel.

The following implement this ABC...
thin raft
slate swan
#

!d discord.abc.GuildChannel.set_permissions

unkempt canyonBOT
#

await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sets the channel specific permission overwrites for a target in the channel.

The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role) that belongs to guild.

The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions) attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.

If the `overwrite` parameter is `None`, then the permission overwrites are deleted.

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

Of a role or a member and a permissions overwrite

#

Not 2 para s

slate swan
#

overwrite is keyword only

#

you pass it as positional

harsh orbit
#

I cannot add more than tow permissions?

slate swan
harsh orbit
#

Wdym

slate swan
#

!keyword

unkempt canyonBOT
#
Positional vs. keyword arguments

Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.

Example

>>> print('Hello', 'world!', sep=', ')
Hello, world!

The first two strings 'Hello' and 'world!' are positional arguments.
The sep=', ' is a keyword argument.

Note
A keyword argument can be passed positionally in some cases.

def sum(a, b=1):
    return a + b

sum(1, b=5)
sum(1, 5) # same as above

Sometimes this is forced, in the case of the pow() function.

The reverse is also true:

>>> def foo(a, b):
...     print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1

More info
Keyword only arguments
Positional only arguments
/tag param-arg (Parameters vs. Arguments)

harsh orbit
#

Can you give me a wa y to solve this error?

slate swan
#

yes, pass it as keyword argument and not positional

ember mango
slate swan
#

its a shell command not python script

ember mango
slate swan
#

yeah

ember mango
#

error

slate swan
mighty turret
#

Hi guys can anyone help me about ticket system in discord.python?

#

ok

hallow fog
#

!e def increment(x): return x+1 def addTo(y): for i in [6,1,-1]: y = bool return y print(range(1))

unkempt canyonBOT
#

@hallow fog :x: Your 3.11 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     def increment(x): return x+1 def addTo(y): for i in [6,1,-1]: y = bool return y  print(addTo(1))
003 |                                  ^^^
004 | SyntaxError: invalid syntax
mighty turret
#
#ticket 

@client.command()
async def ticket(ctx):
    bug_emoji_id = 1140784549249429615 
    bug_emoji= discord.PartialEmoji(animated=True, name='bug', id=bug_emoji_id)
    staffreport_emoji_id = 1140933933870088323 
    staffreport_emoji = discord.PartialEmoji(animated=False, name='staffreport', id=staffreport_emoji_id)
    question_emoji_id = 1140934895812743270 
    question_emoji = discord.PartialEmoji(animated=True, name='questionmark', id=question_emoji_id)
    staff_emoji_id = 1140777915555000470
    staff_emoji = discord.PartialEmoji(animated=False, name='staff', id=staff_emoji_id)
    create_tickettime = datetime.now().strftime("%H:%M:%S")
    close_tickettime = datetime.now().strftime("%H:%M:%S")
    log_channel_name = '🚨ticket-logs'
    log_channel = discord.utils.get(ctx.guild.text_channels, name=log_channel_name)
    if log_channel is None:
        category = discord.utils.get(ctx.guild.categories, name='🎫TICKETS')
        log_channel = await ctx.guild.create_text_channel(log_channel_name, category=category)
#
async def close_callback(interaction, channel):
        if interaction.type == discord.InteractionType.component:
            custom_id = interaction.data['custom_id']
            if custom_id == 'close_select':
                await channel.delete()

                embed = discord.Embed(title='**Ticket Closed**', description='', color=0xFF0000)
                embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/1140644183602888846/1140665041104928889/giphy.gif')
                embed.add_field(name='Εκλεισθει στις:', value=close_tickettime, inline=False)
                embed.add_field(name='Εκλεισθει από τον```
#

async def my_callback(interaction, channel):
        if interaction.type == discord.InteractionType.component:
            selected_value = interaction.data['values'][0]
            guild = interaction.guild
            role2 = discord.utils.get(guild.roles, name='💼 〢Management™')
            role = discord.utils.get(guild.roles, name='⭐〢Staffᵀᴹ')
            member = guild.get_member(interaction.user.id)
            overwrites = {
                guild.default_role: discord.PermissionOverwrite(view_channel=False),
                member: discord.PermissionOverwrite(view_channel=True),
                role: discord.PermissionOverwrite(view_channel=True)
            }

            embed = discord.Embed(title='Ticket Created', description='', color=0x008000)
            embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/1140644183602888846/1140665041104928889/giphy.gif')
            embed.add_field(name='Δημιουργήθηκε από:', value=interaction.user.mention, inline=False)
            embed.add_field(name='Δημιουργήθηκε στις:', value=create_tickettime, inline=False)

            await log_channel.send(embed=embed)

            category = discord.utils.get(guild.categories, name='TICKETS TEST')
            channel = await guild.create_text_channel(f"{interaction.user.name}-ticket", category=category, overwrites=overwrites)
            await interaction.response.send_message(f"Created Ticket - <#{channel.id}>", ephemeral=True)```
hallow fog
#

!e def increment(x): return x+1 def addTo(y): for i in [6,1,-1]: y = bool return y print(range(1))

unkempt canyonBOT
#

@hallow fog :x: Your 3.11 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     def increment(x): return x+1 def addTo(y): for i in [6,1,-1]: y = bool return y  print(range(1))
003 |                                  ^^^
004 | SyntaxError: invalid syntax
mighty turret
#

embed = discord.Embed(title=f"{staff_emoji} Ticket Created", color=0x228B22)
            if selected_value == '01':
                embed.description = f"'Σας ευχαριστούμε πολύ που επιλέξατε να ανοίξετε ένα ticket στον server μας παρακαλώ πείτε μας τον λόγο που ανοίξατε το ticket και σύντομα ένας/μία {role.mention} θα σας εξηπηρετήσει όσο το συντομότερο δυνατό.'"
                embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/1140644183602888846/1140665041104928889/giphy.gif')
            elif selected_value == '02':
                embed.description = f'Σας ευχαριστούμε πολύ που επιλέξατε να ανοίξετε ένα ticket στον server μας παρακαλώ πείτε μας τον λόγο που ανοίξατε το ticket και σύντομα ένας/μία από τους {role.mention} θα σας εξηπηρετήσει όσο το συντομότερο δυνατό.'
                embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/1140644183602888846/1140665041104928889/giphy.gif')
            elif selected_value == '03':
                embed.description = f'Σας ευχαριστούμε πολύ που επιλέξατε να ανοίξετε ένα ticket στον server μας παρακαλώ πείτε μας τον λόγο που ανοίξατε το ticket και σύντομα ένας/μία {role2.mention} θα σας εξηπηρετήσει όσο το συντομότερο δυνατό.'
                embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/1140644183602888846/1140665041104928889/giphy.gif')
            else:
                embed.description = "Unknown option selected."

            lock_emoji_id = 1140935317994623027
            lock_emoji = discord.PartialEmoji(animated=True, name='lockpick', id=lock_emoji_id)
            select2 = Select(
                custom_id='close_select',
                options=[
                    discord.SelectOption(label='Close Ticket', value='01', emoji=f'{lock_emoji}', description='close_ticket'),
                ]
            )```
mighty turret
#

select2.callback = lambda i: close_callback(i, channel)  # Pass 'channel' as the 'channel' argument

            view = View(timeout=None)
            view.add_item(select2)
            await channel.send(embed=embed, view=view)

    # Create the first select menu
    select = Select(
        custom_id='ticket_select',
        options=[
            discord.SelectOption(label='Other', value='01', emoji=f'{question_emoji}', description='other'),
            discord.SelectOption(label='Bug Report', value='02', emoji=f'{bug_emoji}', description='bug report'),
            discord.SelectOption(label='Staff Report', value='03', emoji=f'{staffreport_emoji}', description='staff report')
        ]
    )

    # Set the callback for the first select menu
    select.callback = lambda i: my_callback(i, ctx.channel)  # Pass 'ctx.channel' as the 'channel' argument

    # Create the view and add the first select menu
    view = View(timeout=None)
    view.add_item(select)

    # Send the initial message with the view containing the first select menu
    embed = discord.Embed(title=f"{staff_emoji} **Ticket System**", description="**Ticket |Επικοινωνήστε μαζί μας**\n\n`Καλησπέρα, αν επιθυμείτε να ανοίξετε ένα ticket διαλέξτε την κατηγορία που σας ενδιαφέρει και αυτόματα θα ανοίξετε ένα ticket.`", color=0x228B22)
    embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/1140644183602888846/1140665041104928889/giphy.gif')
    await ctx.send(embed=embed, view=view)```
#

And the error:

 ERROR    discord.ui.view Ignoring exception in view <View timeout=None children=1> for item <Select placeholder=None min_values=1 max_values=1 disabled=False options=[<SelectOption label='Other' value='01' description='other' emoji=<PartialEmoji animated=True name='questionmark' id=1140934895812743270> default=False>, <SelectOption label='Bug Report' value='02' description='bug report' emoji=<PartialEmoji animated=True name='bug' id=1140784549249429615> default=False>, <SelectOption label='Staff Report' value='03' description='staff report' emoji=<PartialEmoji animated=False name='staffreport' id=1140933933870088323> default=False>]>
Traceback (most recent call last):
  File "C:\Users\DrattonGR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\DrattonGR\Desktop\DISCORD BOTS\Energy Roleplay\main.py", line 128, in my_callback
    channel = await guild.create_text_channel(f"{interaction.user.name}-ticket", category=category, overwrites=overwrites)
  File "C:\Users\DrattonGR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 1369, in create_text_channel
    data = await self._create_channel(
  File "C:\Users\DrattonGR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 1227, in _create_channel
    payload = {'allow': allow.value, 'deny': deny.value, 'id': target.id}
AttributeError: 'NoneType' object has no attribute 'id'```
#

@pastel plank

hallow fog
#

!e def increment(x):
return x+1

def addTo(y):
for i in [6,1,-1]:
y = range(y)
return y

print(addTo(1))

unkempt canyonBOT
#

@hallow fog :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 9, in <module>
003 |     print(addTo(1))
004 |           ^^^^^^^^
005 |   File "/home/main.py", line 6, in addTo
006 |     y = range(y)
007 |         ^^^^^^^^
008 | TypeError: 'range' object cannot be interpreted as an integer
hallow fog
#

!e def increment(x):
return x+1

def addTo(y):
for i in [6,1,-1]:
y = int(y)
return y

print(addTo(1))

unkempt canyonBOT
#

@hallow fog :white_check_mark: Your 3.11 eval job has completed with return code 0.

1
slate swan
hallow fog
#

!e def increment(x):
return x+1

def addTo(y):
for i in [6,1,-1]:
y = int(y)
return y

print(int(1))

unkempt canyonBOT
#

@hallow fog :white_check_mark: Your 3.11 eval job has completed with return code 0.

1
slate swan
#

dont spam this channel

cloud dawn
#

You'd need to use oauth then and do it from there.

#

Hikari prob has the best resources/docs for this. Hikari also offers a restapi that can work alongside discord.py

#

Discord.py used to have IPC routes and discord quartz for the routes but idk if that has been maintained

#

Yes but it also offer standalone support for a dashboard. That way you could combine it with discord.py

#

It support the logging in part and getting your bots resources guilds/ user info etc l you would still need to make the site yourself ofc

#

I guess you could pair it with fastapi never tried but it should be good

#

Just have it sync to dev guild for development and sync it globally when pushing to production.

#

Np! Been a year since I worked with a dashboard but if you have any issues just ping me.

#

Well you said some command already work, did you add the new commands to the tree?

turbid condor
#

Sync?

cloud dawn
#

A did you add the new extension to the bot?

modern fiber
#

How to do this timestamp (relative)?

#

Such as today at...

slate swan
#

It would be today at if it would be actually today

cloud dawn
#

Yeah prob best to use a Discord timestamp

slate swan
#

If its not showing correct time based on your timezone you need to specify it

cloud dawn
#

Gotta go work again gl @slate swan

slate swan
#

or should i say i should be

modern fiber
#

thanks

#

also i have one more question

modern fiber
#

how can I make it so when someone replies to a bot's message, it also makes it an embed but bot replies to it's own message

#

if that makes sense

slate swan
#

you would need to store the message id corresponding to message id containing bot embed

#

in database or something

#

and then if message is a reply you lookup in your database what is the embed corresponding that message and reply to the embed you got id of

harsh orbit
slate swan
# harsh orbit Example pls

!e ```py
def some_func(positional_or_keyword, *, keyword_only):
...

some_func(123, keyword_only=456) # valid
some_func(positional_or_keyword=123, keyword_only=456) # valid
some_func(123, 456) # not valid

unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 7, in <module>
003 |     some_func(123, 456) # not valid
004 |     ^^^^^^^^^^^^^^^^^^^
005 | TypeError: some_func() takes 1 positional argument but 2 were given
harsh orbit
#

Why there is this example in docs

overwrite = discord.PermissionOverwrite()
overwrite.send_messages = False
overwrite.read_messages = True
await channel.set_permissions(member, overwrite=overwrite)

I exactly did this and the error happened

slate swan
harsh orbit