#discord-bots

1 messages ยท Page 252 of 1

potent spear
#

loading extensions also became async, but that's on dpy, I don't know about forks

slate swan
#

my json file look like this :

{
  "219550798864973824",
  "1111504619076599808"
}
buoyant quail
#
                mentioned_ids = [mention.id for mention in message.mentions]
                if any(str(user_id) in mentioned_ids for user_id in ids):

i believe mention.id is returning integer, not string

potent spear
slate swan
#

so without the quotes ?

potent spear
#

I'd just rewrite and actually use a DB tbh

slate swan
potent spear
slate swan
slate swan
#

the ping code

#

i sent before

potent spear
#

so, you can google that error actually, the answer is quite simple

buoyant quail
#

!e

import json 
print(json.loads("""
{
  "219550798864973824",
  "1111504619076599808"
}
"""))
unkempt canyonBOT
#

@buoyant quail :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 2, in <module>
003 |     print(json.loads("""
004 |           ^^^^^^^^^^^^^^
005 |   File "/usr/local/lib/python3.11/json/__init__.py", line 346, in loads
006 |     return _default_decoder.decode(s)
007 |            ^^^^^^^^^^^^^^^^^^^^^^^^^^
008 |   File "/usr/local/lib/python3.11/json/decoder.py", line 337, in decode
009 |     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
010 |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
011 |   File "/usr/local/lib/python3.11/json/decoder.py", line 353, in raw_decode
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/vuwekurepi.txt?noredirect

potent spear
slate swan
#

i can read

buoyant quail
#

Make it a list or a dict. There are no sets in json

[
  219550798864973824,
  1111504619076599808
]
slate swan
#

i want to save it later

#

like making a command that save it (like -activate_dontpingme)

#

and i tried using a list but not working

#

like this :

ids = ["1111504619076599808"]```
buoyant quail
#

you are still casting it to string in the any

slate swan
#

so i need to remove it ?

buoyant quail
#

yeah (and make them ints in the file)

#

or cast the mention ids to string too

slate swan
#
const { Client, Intents } = require("discord.js");

console.log("Bot is starting...");

const client = new Client({
  intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});

console.log(client);

const prefix = "!";

client.on("messageCreate", (message) => {
  if (!message.content.startsWith(prefix) || message.author.bot) return;

  const args = message.content.slice(prefix.length).trim().split(/ +/);
  const command = args.shift().toLowerCase();

  if (command === "word") {
    if (args.length > 0) {
      const word = args[0];
      message.channel.send(`The word you entered is: ${word}`);
    } else {
      message.channel.send("No word provided. Please enter a word after the command.");
    }
  }
});

client.login(token);

Bot is starting...
/Users/ericfloyd/github/Bot/src/bot.js:5
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
^

TypeError: Cannot read properties of undefined (reading 'FLAGS')
at Object.<anonymous> (/Users/ericfloyd/github/Bot/src/bot.js:5:23)
at Module._compile (node:internal/modules/cjs/loader:1254:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
at Module.load (node:internal/modules/cjs/loader:1117:32)
at Module._load (node:internal/modules/cjs/loader:958:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47

Node.js v18.16.0

#

working

slate swan
#

oops

#

any ts/js server?

slate swan
#

how to respond to a non-interaction message ?

#

i searched the doc

slate swan
#

!d discord.Message.reply

unkempt canyonBOT
#

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

A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message").

New in version 1.6.

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

oh yeah

#

!d discord.TextChannel.send

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

Sends a message to the destination with the content given.

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

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

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

so message.reply("message") ?

slate swan
#

okey

#

thnks

smoky sinew
#

** ๐Ÿ˜”

slate swan
#

Add buttons instead of reactions

#
    # This one is similar to the confirmation button except sets the inner value to `False`
    @discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
    async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('Cancelling', ephemeral=True)
        self.value = False
        self.stop()```
this?
#

The entire file is relevant

#

Not just "this"

#

oh but buttons, like, they are per user, no?

#

No, anyone can click them

#

well yes but 2 ppl can click them

#

they are only clickable once, no?

#

They're just like reactions

slate swan
#

And once it's set to disabled, nobody can click it

#

okey okey

#

so what will be better for this scenario. I am asking something but i want like a confirmation, since when "yes" is pressed there is no way to undo. So before u had to write !yes twice, so mistakes were less likely. Now i was moving to emoji, and getting the count. But the other option is buttons. What would u use?

#

Buttons are much easier to work with

#

Not sure how different it is to reactions

#

In the end it's the same interaction from the user, just in a better UX way

#

yeah, but u dont have like a count for how many times someone pressed "yes"

#

with emojis, must be different ppl tho

#

You can, create a counter

#

with the !yes, same user could write it multiple times

#

im pretty sure with button u can count them too

#

So every time u press yes, i add 1 to a counter?

#

and u can press it again?

#

i see, so i guess buttons ๐Ÿ˜„

#

Much better imo, yeah

#

btw...

#
    perms = ctx.channel.permissions_for(ctx.me)
    if not perms.send_messages:
        return```
This code is useless right?
#

Like, discord api will already return if bot doesnt have perms

#

right?

#

discord api will already return if bot doesnt have perms
Meaning?

#

if i call a command which is supposed that the bot will send "hello world"

#

it wont if it doesnt have the perms

#

It will throw an error

#

yeah, but only me will see such error on the console, right?

#

It will get logged unless you have an error handler that "eats" all errors and prevents them from being logged

#

i see, but bot wont disconnect, no?

#

so idk if those liens are good practice or useless

#

Nope, will not get disconnected

#

Usually you'd have a global error handler handling such errors

#

then i remove

#

thanks

slate swan
smoky sinew
#

type hint your code :D

tight coral
#

Hey this for anyone, I'm looking for people to help work on my bot, it's a multipurpose security bot and orentinated around fivem. Anyone interested it used discord.py so lmk.

slate swan
#

how can i disable all buttons at once when certain condition is met?

smoky sinew
#

and set disabled to True

#

you can also set the view to None instead which sometimes looks cleaner

slate swan
#

but how? ๐Ÿ˜ฎ

#

!d discord.ui.View.children

unkempt canyonBOT
slate swan
#

Loop through this list (checking if each item is a button) and set disabled to True

#

ugg

#

and what if someone want to disable specific buttons only?

smoky sinew
slate swan
#

but how do i know which button is what xD

smoky sinew
#

it's custom_id

slate swan
#
class Counter(discord.ui.View):
    @discord.ui.button(label=str(DENIES), style=discord.ButtonStyle.danger)
    async def button1(self, interaction: discord.Interaction, button: discord.ui.Button):

    @discord.ui.button(label=str(APROVS), style=discord.ButtonStyle.blurple)
    async def button2(self, interaction: discord.Interaction, button: discord.ui.Button):```
#

I have them like this now

slate swan
smoky sinew
#

i'm not in the dpy server

slate swan
#

mmm, children is a property, but it is a list according to docs, i still cant loop it (?)

#

property children
The list of children attached to this view.

Type
List[Item]

#

?

#

he is

#

but i dont see the point of posting that here tbh

lethal drift
#

tf dude

#

you need help

slate swan
#

he needs

#

and u too

smoky sinew
#

<@&831776746206265384>

slate swan
#

bro xdddd

#

look when i created this discord account

#

xd

fierce crag
#

!mute 1110599386645418105 incident_investigating

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied timeout to @slate swan until <t:1686620865:f> (1 hour).

fierce crag
#

!ban 1110599386645418105 DMing members in this fashion is absolutely not appropriate

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied ban to @void anchor permanently.

turbid condor
#

A question is it possible to fetch the date at which a member is given the role??

#

If yes then how can i fetch it?

daring olive
#

!unban 1110599386645418105 banned in error

unkempt canyonBOT
#

:ok_hand: pardoned infraction ban for @void anchor.

sick birch
#

Which I would not recommend

#

I believe certain events do give you which a member's roles are updated, then it would just be the current time

turbid condor
#

Yeah it would make the rate limited

#

So no way to find out except going through the audit logs which means that's a no

sick birch
#

I mean, you could also listen for a on_member_update event

#

I believe discord.Role objects are hashable so you can set() both before.roles and after.roles and subtract them

#

I.e set(after.roles) - set(before.roles) should give you the roles that were added to a user

turbid condor
#

wouldn't that only fetch the roles that have been whereas I am trying to get the date at which the roles were added

sick birch
turbid condor
#

hmm

verbal shuttle
#

When dealing with the date and time what setting allows the time to be in channels?

#

Example ^

verbal shuttle
sick birch
#

It's not a special Discord thing

verbal shuttle
#

Is there a way to change the time automatically when setting it up

sick birch
#

There a function to change the channel's name, yes

#

!d discord.TextChannel.edit

unkempt canyonBOT
#

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

Edits the channel.

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

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

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

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

Can be pretty much any discord.abc.GuildChannel iirc

verbal shuttle
#

Ok another thing I need help with is do you know where I can find a python code that explains how to set up anti-link , anti-raid, antispam etc

#

I've been searching for 2 days have not been able to locate a recent help.

#

The one I found has an @client error

sick birch
#

For instance @inland quail is our security bot and it's closed source, while most of our other bots are all open source

verbal shuttle
#

In a way that does make sense ๐Ÿ˜‰

sick birch
#

Yeah, if people publish their security stuff it's too easy for threat actors to use that against them

#

So most of the time you either have to opt in to use a prebuilt security solution or try to roll your own

verbal shuttle
#

Roll our own.... Need more lessons on how python works.

#

Thank you

vale wing
verbal shuttle
#

Thank you ๐Ÿ˜Š

vale wing
#

Np, only asking for a star in return

verbal shuttle
#

How to star โญ

vale wing
#

There's that star button in repo

mild lava
#

i've been trying to rewrite my discord bot to work in a more stateless way, but im confused on some points. if i create a view and send it to a channel, then the bot restarts, does the bot still correctly call the on_timeout method of my view class, and if so how if the instance no longer exists?

#

then, if i want to tie an instance of a view to a channel, such that i can retain the channel's id after a restart, what would be the best way of doing that?

vale wing
mild lava
#

what about buttons, does the bot stop listening to non-persistent ones after restarting as well?

vale wing
mild lava
#

i'll try to describe my use case in a simplified way, bear with me

vale wing
#

I hope it's more clear now

#

When the bot restarts, all runtime data is deleted, including that mapping storing component ids and callbacks

mild lava
vale wing
#

I don't really understand concept of state in context of discord views sorry

mild lava
#

stateless in my case means i want to be able to restart the script without the bot losing its place

#

i.e. any data it needs to function can be retrieved at interaction time from data provided by the discord api, and in my case additionally data fetched from a database based on the previously mentioned data from the discord api

#

give me a second to write out an explanation of my app, hopefully it will make it more clear what im trying to do

#
  1. users interact with my bot by first running a command (/start).
  2. the bot responds with a view that contains some information about a "game" instance that is in its initialization phase, and a button that lets users open a "menu" message.
  3. this ephemeral menu message is the second view, where depending on the user's role, it shows buttons to join, leave, start, or stop the game.
  4. once a user presses the "start" button, the bot starts sending the third view repeatedly, which contains the actual gameplay. each of these gameplay views is simply a button that gets pressed, then the view is no longer needed, and a new one is sent
#

perhaps you might have some ideas on how to restructure this or point out flaws

vale wing
#

There are two ways

Persistent view

  1. You define view class
  2. You use bot.add_view(view)
  3. Library adds components
  4. You can send view later any time, as components callbacks are registered on startup it will always respond. Just make sure that all components have custom_id set.

Raw interactions

Suitable for things like button roles where you don't have constant view with constant components

  1. You send a view without callbacks, just with components, each has custom_id set
  2. You create that mapping of custom_id to callback or whatever you want to map it to

When user presses the component

  1. You receive interaction event
  2. You compare received custom_id with data in your mapping and do action based on it
vale wing
mild lava
#

maybe raw interactions would work, if i would allow me to separate the button logic from my view classes

vale wing
#

If bot restarts it's gonna be down for a while and user will prob leave the game after they receive a couple of "application didn't respond" errors

mild lava
#

the "state" here is basically the state of the game. i've already written some code to persist this state to a file/db/remote location so it can be retrieved after a restart

#

in my case, the downtime isnt really the problem (my vm or host takes a couple minutes to restart, and if the script crashes for whatever reason thats even faster). the larger problem is i might have multiple bot instances serving requests behind a load balancer, or i might even have the bot running on a serverless platform. in order to make that possible, i first need to solve the problem of allowing the bot process to restart without losing any information

vale wing
#

You may just do restart by reloading extensions

mild lava
#

on a serverless platform (e.g. vercel) i dont have control over how to restart it, it simply shuts down the process after the http request is complete

glad cradle
#

and iirc they should only be supported by disnake in the base API

turbid condor
#

How to check a user status? like whether he's online, idle, dnd or invisible??

naive briar
#

!d discord.User

unkempt canyonBOT
#

class discord.User```
Represents a Discord user.

x == y Checks if two users are equal.

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

hash(x) Return the userโ€™s hash.

str(x) Returns the userโ€™s handle (e.g. `name` or `name#discriminator`).
turbid condor
#

that's discord.Member.status

#

!d discord.Member.status

unkempt canyonBOT
#

property status```
The memberโ€™s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") instead.
turbid condor
#

but It always returns offline

glad cradle
#

!d discord.Intents.presences iirc you need this intent

unkempt canyonBOT
#

Whether guild presence related events are enabled.

This corresponds to the following events:

โ€ข on_presence_update()

This also corresponds to the following attributes and classes in terms of cache...

turbid condor
#

hmm i have all enabled

#

i'll recheck my code

naive briar
#

!d discord.Intents.presences

#

๐Ÿซ 

slate swan
#
                        channel = bot.get_channel(channel_to_send_messages)
                        em = discord.Embed(color=0xFFD700)
                        em.add_field(name='Current Not Expired Keys', value=f'<@{user}> key isnt expired' + "\n" + "expire date: " + expire + "\n" + "Key: " + key)
                        await channel.send(embed=em)    ```

the code above keep sending the non expired keys non stop how can i make it send each non expired key only once?
upbeat otter
slate swan
slate swan
#

and while true

upbeat otter
#

yes that's the reason

#

while True is a loop

slate swan
slate swan
upbeat otter
#

so consider the consequences if any

slate swan
#

so it will give only one of the Not expired keys?

upbeat otter
#

yeah

slate swan
quasi hill
#

hi can someone help me with a bot i just ran and i dont know how to shut it down i was tryna make on on repl it

upbeat otter
upbeat otter
#

of the replit window

quasi hill
#

i click stop but the bot still online :/

#

oh wait it takes time

upbeat otter
slate swan
quasi hill
#

oh yeah its not instant as like runiing it off a freind server

upbeat otter
slate swan
quasi hill
#

@upbeat otter ty for clearin tht up i was confused af

upbeat otter
#
expired_keys = get_expired_keys() #This is an iterable of the expired keys
for key in expired_keys:
  await send(key)

# This is the same as below but a lot cleaner

i = 0 
while i < len(expired_keys):
  await send(expired_keys[i])
  i += 1
slate swan
#

kk ty

#

hello

upbeat otter
#

Hi

slate swan
#

i just made my first discord bot, but it wont send messages

upbeat otter
#

so sad D7_Pensive

#

what's the error

slate swan
#

# IMPORT THE OS MODULE.
import os

# IMPORT LOAD_DOTENV FUNCTION FROM DOTENV MODULE.
from dotenv import load_dotenv

# LOADS THE .ENV FILE THAT RESIDES ON THE SAME LEVEL AS THE SCRIPT.
load_dotenv()

# GRAB THE API TOKEN FROM THE .ENV FILE.
DISCORD_TOKEN = "TOKEN GOES HERE"

# GETS THE CLIENT OBJECT FROM DISCORD.PY. CLIENT IS SYNONYMOUS WITH BOT.
bot = discord.Client(intents=discord.Intents.default())

# EVENT LISTENER FOR WHEN THE BOT HAS SWITCHED FROM OFFLINE TO ONLINE.
@bot.event
async def on_ready():
    # CREATES A COUNTER TO KEEP TRACK OF HOW MANY GUILDS / SERVERS THE BOT IS CONNECTED TO.
    guild_count = 0

    # LOOPS THROUGH ALL THE GUILD / SERVERS THAT THE BOT IS ASSOCIATED WITH.
    for guild in bot.guilds:
        # PRINT THE SERVER'S ID AND NAME.
        print(f"- {guild.id} (name: {guild.name})")

        # INCREMENTS THE GUILD COUNTER.
        guild_count = guild_count + 1

    # PRINTS HOW MANY GUILDS / SERVERS THE BOT IS IN.
    print("SampleDiscordBot is in " + str(guild_count) + " guilds.")

# EVENT LISTENER FOR WHEN A NEW MESSAGE IS SENT TO A CHANNEL.
@bot.event
async def on_message(message):
    # CHECKS IF THE MESSAGE THAT WAS SENT IS EQUAL TO "HELLO".
    if message.content.lower() == "hello": 
        # SENDS BACK A MESSAGE TO THE CHANNEL.
        await message.channel.send("hey dirtbag")

# EXECUTES THE BOT WITH THE SPECIFIED TOKEN. TOKEN HAS BEEN REMOVED AND USED JUST AS AN EXAMPLE.
bot.run(DISCORD_TOKEN)
#

i copied it from some website, i just want to get basics working lol

upbeat otter
#

omg

slate swan
#

i dont get an error, it starts, says its connected but when i send hello

#

it doesnt do anyrhing

#

uh oo did i do smth wrong lol

upbeat otter
#

what you're doing is all wrong ๐Ÿ’€

slate swan
#

lmao

upbeat otter
#

stop copying

#

atleast

slate swan
#

okie

#

i gtg sorry

upbeat otter
#

by

slate swan
#

cya later

slate swan
#

@upbeat otter are you oneline? could you help me out a bit?

slate swan
#

so could you tell me how to do it the right way?

#

or just send some resrouces or so

#

!resources

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.

upbeat otter
#

hm wait

#

it's full of "good" examples

slate swan
#

okay thank you ๐Ÿ˜„

#

๐Ÿ™‚

upbeat otter
halcyon magnet
#

Hi guys ,which discord python api wrapper is recommended to use these days?

slate swan
reef fractal
#
@client.tree.command(name = "hello", description="prints hello")
async def hello(interaction: discord.Interaction):
    user_id = interaction.author.id
    user_name = interaction.author.name
    
    data = {"content": f"User{user_name}({user_id}) used the /hello command."}
    
    response = requests.post(webhook_url, json=data)
    await interaction.response.send_message("Hello", ephemeral=False) ```

Can anyone please help me with this?
slate swan
#

"this" is very informative on what doesn't work ThumbsUp

reef fractal
#

The user_id part, and user_name part

#

is that right?

slate swan
#

tias

#

Spoiler: There is no author attribute, see the list

unkempt canyonBOT
#

class discord.Interaction```
Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

New in version 2.0.
naive briar
#

!d discord.Interaction.user

unkempt canyonBOT
naive briar
#

But there is user ๐Ÿ˜Ž

slate swan
#

And that's why people should learn to find such things themselves

unique lichen
#

i know i shouldnt be asking here but doing in discord bot

okay so what i am doing is theres a list in a['f']
i want to remove something from a['f]

when i used .remove() it returns null

reef fractal
#

the author attribute ran when using ctx, but it didn't with interaction, anywayss, thank you for telling me

unique lichen
slate swan
unique lichen
#

opening a thread for it seemed too much , general sounds better

radiant bough
#

In on_message_edit event is it possible to know if the message was sent when an application was executed?
If so, how can I get the user who executed the app command

halcyon magnet
#

Guys whats difference between slash command and tree command?

slate swan
#

discord.py doesn't have a slash command decorator, so there can't be a difference between something that exists and something that doesn't - hence the tree command decorator represents a slash command

halcyon magnet
#

But why it's name is tree command

pearl musk
#

if you can make discord bot for me dm (150-200$)

golden portal
#

no one is calling it a tree command, if you meant CommandTree, thats the object that holds all app commands (slash commands) and context menus, its just mapping, and handle proper invocation to those attached commands/menus

slate swan
torpid frigate
#

how do I give my bot perms to manage messages. it cant delete messages on the main server but works in my private test server

slate swan
#

it's a per-server permission
You need to go into the main server's role settings and enable the permission for your bot's role

torpid frigate
#

ty its worked

slate swan
#

Np

slate swan
unkempt canyonBOT
#

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

turbid condor
#

is there a way to check what badges a user has?

turbid condor
#

ok thx

glad cradle
turbid condor
#

yes

glad cradle
#

!d discord.User.public_flags

unkempt canyonBOT
turbid condor
#

now i see why i missed those

#

i was searching for badge

dry kelp
#

So i am having issues with my handlers for antinuke.

#

sends missing permissions error because is trying to ban himself (the bot)

#

the user was whitelisted so it wasn't supposed to be kicked

twilit grotto
potent spear
#

these handle functions all return None...

#

you probably want them to return either True or False?

smoky sinew
foggy bone
#

hello, I want to build a discord bot in python that would allow me to display my League of Legends stats in a dedicated channel. I'm an extreme beginner in python and here's my code, no particular error message but nothing happens in the discord and on the terminal. Does anyone have a solution? Is it in the API? if someone says, you can dm me pls! thx team!!!

potent spear
#

Youโ€™re missing message_content intents. Theyโ€™re not the same as .messages Intents

#

!intents

unkempt canyonBOT
#
Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

slate swan
#

fix?

#

Can't help you find a fix unless you show us the code that's causing the error

unkempt canyonBOT
#

@sick birch :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     None.url
004 | AttributeError: 'NoneType' object has no attribute 'url'
smoky sinew
#

NoneType object has no attribute 'fix'

sick birch
#

if only

glad cradle
slate swan
#

why buttons are slower to "process" than reactions?

foggy bone
# potent spear Your intents are the issue

ok, i change the code and i have this in my terminal now:
2023-06-13 21:40:45 INFO discord.client logging in using static token
2023-06-13 21:40:47 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: e8accedf9f130078248c763a262e2e61).
Connectรฉ en tant que bot
Une erreur s'est produite : 'win_ratio'

slate swan
#

the first 2 lines mean the bot is online

foggy bone
#

and the begining is now like this :

slate swan
#

the others idk, cant read frrench

foggy bone
#

in french is like "the bot is online"

#

i don't understand the "win_ratio"

slate swan
#

thats something from u, i believe

foggy bone
#

une erreur s'est produite is like "there is an error: "win_ratio"

slate swan
#

Then go to win_ratio and check what's wrong there

#

it's not defined thi ( or the key doesnt exist , idk french)

#

Instead of having such abstract logging you could log the error itself

#

one thing. If on a view im adding buttons, can i have the stored somewhere so from 1 button i can change others?

slate swan
#

what? if my button is async def button_no(self, interaction: discord.Interaction, button: discord.ui.Button): I can call it like self.button_no ????

#

right, self being the same View class instance

#

If it's in a view, yes

#

and then .label or .disable?? ๐Ÿ˜ฎ

#

Yep, that's how OOP works

#

oh well, for me OOP is more like class Whatever: ... ; something = Whatever()

#

It is as well

#

i guess button_no is the constructor of such button? but like static object?

foggy bone
#

"win_ratio" just on this page, there is a probleme??? or was a probleme with the keys?

slate swan
#

cuz everytime i call self.button_no i am refering to the same button, no? XD

slate swan
#

yeah but, what i mean is on normal OOP
x = Number(2)
y = Number(2)
x and y are totally different objects

slate swan
slate swan
#

In that entire class you can access those entire things

#

That's OOP

#

yeah, and by doing x.label = 'hello' wont change y.label

#

but seems here, with buttons, doing self.button_no is always the same object (?)

#

๐Ÿคจ so you're trying to edit one view's button by another?

slate swan
#

like, i am testing with a counter. When ever it reaches 0, i wanna disable the other button

slate swan
#

i could disable all children, but wanted to disable specific button

foggy bone
#

and ecept?

slate swan
#

u can copy paste this testing code

#
class Counter(discord.ui.View):

    def disable_button(self, custom_id):
        for child in self.children:
            if isinstance(child, discord.ui.Button) and child.custom_id == custom_id:
                child.disabled = True

    # Define the actual button
    # When pressed, this increments the number displayed until it hits 5.
    # When it hits 0, the counter button is disabled, and it turns green.
    # note: The name of the function does not matter to the library
    @discord.ui.button(label=str(DENIES), style=discord.ButtonStyle.danger, custom_id='no')
    async def button_no(self, interaction: discord.Interaction, button: discord.ui.Button):
        c = int(button.label) or DENIES
        if c - 1 <= 0:
            button.label = 'NO'
            button.style = discord.ButtonStyle.red
            button.disabled = True
            self.disable_button('yes')
        else:
            button.label = str(c - 1)

        # Make sure to update the message with our updated selves
        await interaction.response.edit_message(view=self)

    @discord.ui.button(label=str(APROVS), style=discord.ButtonStyle.blurple, custom_id='yes')
    async def button_yes(self, interaction: discord.Interaction, button: discord.ui.Button):
        c = int(button.label) or APROVS
        if c - 1 <= 0:
            button.label = 'YES'
            button.style = discord.ButtonStyle.green
            button.disabled = True
            self.disable_button('no')
        else:
            button.label = str(c - 1)

        # Make sure to update the message with our updated selves
        await interaction.response.edit_message(view=self)```
slate swan
#

yeah

#

they are, what's the issue then?

#

on the same View

#

well, i am not saying there is a problem XD just wanted to understand whats going on. When i call self.button_no i am refering to the object button_no, but i have never created such object

#

self there represents a View class, that store's the buttons as attributes button_no and button_yes

slate swan
#

yeah, but i havent done anywhere x = button_no()

#

That's for what decorators are made for

#

Oh

#

decos create an object with the function u define as constructor?

#

srry never used decos before ๐Ÿ˜ฆ

#

No, decorators execute the function that is defined in that decorator

#

aaa

slate swan
unkempt canyonBOT
#

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

1
slate swan
#

mmm not sure whats going on. foo is getting overwritten

#

Not the best example

#

Though that goes off-topic for the channel, there are some better channels if you need some better explanation of decorators - or your favorite search engine

#

ok ok, srry

#

so, a few days ago i asked chat gpt and he wrote me this

#
async def ui(ctx):
    button1 = discord.ui.Button(style=discord.ButtonStyle.primary, label='Button 1')
    button2 = discord.ui.Button(style=discord.ButtonStyle.primary, label='Button 2')

    view = discord.ui.View()
    view.add_item(button1)
    view.add_item(button2)

i know probably u dislike AI tools, but still, this is why i asked about "storing" buttons somewhere

unkempt canyonBOT
#

10. Do not copy and paste answers from ChatGPT or similar AI tools.

slate swan
#

well, i know, but still, lets say i wanna disable 10 buttons only, what will be the best way? 10 lines calling self.button_x.disabled = True?

slate swan
#

yeah srry, let say i have 20 buttons. How do i filter them?

#

Custom IDs

#

and do i have to loop over all of them to see which ones match the id or can i directly choose it?

#

If you know which one precisely (the function that holds the button), you can use just edit whatever you want on it

#

Otherwise for the custom ID yes, loop and condition

#

well ok, i think im not explaining myself or there is no way to do it the way i want. Imma try my best. So, when u create 10 objects, each of them is assigned to a variable. Then u can refer to certain object by its variable. Here, if i had a,b,c,d,e,f buttons, i could, inside the method for button e, call a.label="hi" and b.label = "bye". using a and b as variables, instead of self.imagine_my_button_has_a_big_name.label="hi" and self.imagine_my_button_has_a_big_name.style = discord.ButtonStyle.red. For example

solid crater
#

How can I make a command for add roles? For example: /addrole

slate swan
#

pretty sure u can

sick birch
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 "discord.Role")s.

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

and how it's wrong in this code?

#
        name="addrole",
        description="Agregar un rol a un usuario.",
    )
    @commands.has_permissions(manage_roles=True)
    @commands.bot_has_permissions(manage_roles=True)
    @checks.not_blacklisted()
    @app_commands.describe(
        user="El usuario que debe tener un nuevo apodo.",
        role="El rol que desea ponerle.",
    )
    async def addrole(self, c, m: discord.Member, role1: "<@&1115234290905653335>" = None):
       
        member = context.guild.get_member(user.id) or await context.guild.fetch_member(
            user.id
        )
        try:
            await member.add_roles(role)
            embed = discord.Embed(
                description=f"El nuevo rol de **{member}** es **{role}**!",
                color=0x9C84EF,
            )
            await context.send(embed=embed)
        except:
            embed = discord.Embed(
                description="Ocurriรณ un error al intentar agregar el rol al usuario. Asegรบrese de que mi rol estรฉ por encima del rol del usuario al que desea agregar el rol.",
                color=0xE02B2B,
            )
            await context.send(embed=embed)



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

because it don't works

fading marlin
#

it should be a discord.Role object, not a string or None

solid crater
rapid snow
#

We generally don't do that. We want you to learn from the experience.

solid crater
slate swan
#

there are better ways to learn python tho

solid crater
#

but I want learn discord moderation, and the bots it's the thing that I want to learn the first

slate swan
#

well, u gotta go step by step. First learn programming in general, then specific language (python), and then move into python discord bots

solid crater
#

can you say me any way to learn python?

slate swan
#

u cant run before walking

#

well, u can go #python-discussion and ask for resources there, pretty sure ppl know good web pages

solid crater
#

okay

solid crater
slate swan
#

if it was, it would work

solid crater
#

me

potent spear
#

the fact that you're using c in your function parameters and then use context as variable can't be right

#

if you understand what that means...

solid crater
slate swan
#

? it does not work. u literally said

solid crater
#

not works that command

slate swan
#

then it doesnt work

#

๐Ÿคทโ€โ™€๏ธ

solid crater
#

but the bot have a lot of commands that yes works

#

I said my BOT is pretty good, not the command

slate swan
#

yeah so u have a top tier car with awesome chasis without 1 wheel. Still pretty good car, right?

solid crater
#

bruh

#

The bot have all this commands

#

the only command that not work is the /addrole

slate swan
#

okey man, ur bot is pretty good ๐Ÿ‘

solid crater
#

Yes.

solid crater
#
        name="addrole",
        description="Agregar un rol a un usuario.",
    )
    @commands.has_permissions(manage_roles=True)
    @commands.bot_has_permissions(manage_roles=True)
    @checks.not_blacklisted()
    @app_commands.describe(
        user="El usuario que debe tener un nuevo apodo.",
        role="El rol que desea ponerle.",
    )
    async def addrole(self, c, m: discord.Member, role1: "<@&1115234290905653335>" = None):

        try:
            await member.add_roles(role)
            embed = discord.Embed(
                description=f"El nuevo rol de **{member}** es **{role}**!",
                color=0x9C84EF,
            )
            await context.send(embed=embed)
        except:
            embed = discord.Embed(
                description="Ocurriรณ un error al intentar agregar el rol al usuario. Asegรบrese de que mi rol estรฉ por encima del rol del usuario al que desea agregar el rol.",
                color=0xE02B2B,
            )
            await context.send(embed=embed)



async def setup(bot):
    await bot.add_cog(Moderation(bot))
potent spear
#

in the docs, they use ctx
it's up to you
so use that in as parameter name
as well as ctx.send(...)
instead of context...

slate swan
#

i think he doesnt know what is he doing, tbh

potent spear
#

no offense, but not sure how you could make these mistakes if you already have multiple commands and cogs

solid crater
slate swan
#

so u made 20+ commands without knowing programming? damn im jelous. I wish i could

solid crater
#

yes

#

because people help me

smoky sinew
# solid crater

all copied and pasted using someone else's code i'm guessing

solid crater
#

to do that

#

if it were copied and pasted, I would not have the problem when doing this command

slate swan
#

?

#

u literally asked someone to copy ur code, fix it, and paste again

solid crater
#

yes

#

He is saying that all the commands are copied and pasted

#

but if it were copied and pasted, I would not have the problem when doing this command

#

Well, since you don't help me I'm not going to argue anymore, I'd rather learn than argue with such an incompensable community

slate swan
#

we help, we dont spoonfeed

solid crater
#

you are not helping me

#

the only person that helps me is @potent spear

slate swan
#

i am not writting ur code for u

solid crater
#

okay

#

I understand that

#

since you don't want to do it, you don't have to start to hesitate

thin raft
#

you can ask if you get any errors, learn something you dont udnerstand etc

#

not for people writing you code

solid crater
#

@slate swan because from the first message you sent me everything has been critical. Have you ever wanted to learn, just like me

solid crater
slate swan
smoky sinew
solid crater
#

I understand, sorry fot that

slate swan
solid crater
solid crater
#

That's why I wanted someone help me

slate swan
#

i still wonder how u managed to add some many commands without understanding very well the documentation

slate swan
#

pretty sure there are tutorials about adding/removing discord roles

solid crater
#

my code was like this but a man told me it was wrong and he corrected it for me the way i have sent before

slate swan
#

Lets say my bot sends a message when calling a command. This message uses variables like name or index. How could I edit the message text and still have access to those variables inside a View class (when pressing a button)? For example, bot ask if name is equal to index idx, and u have 2 buttons, yes and no. If u press yes, text is changed to f"This {index} is {name}". Inside the ui.View i dont have the variables name and index

solid crater
#

no

#

but np

slate swan
#

'Perfect Choice, Please send the amount to this CashApp ', {cashapp}
TypeError: unsupported operand type(s) for +: 'set' and 'str'

#

ffix?

slate swan
#

seems u are trying to sum a set and a string

slate swan
# smoky sinew no, code

elif message.content.lower() == 'cash app':
await message.channel.send(
'Perfect Choice, Please send the amount to this CashApp ', {cashapp}
+ (message.author.mention))

upbeat gust
#

why do you have {cashapp}

upbeat gust
#

and the () around message.author.mention

slate swan
slate swan
upbeat gust
smoky sinew
slate swan
#

await coro(*args, **kwargs)
File "/home/container/soul.py", line 144, in on_message
'Perfect Choice, Please send the amount to this CashApp ' + {cashapp}
TypeError: can only concatenate str (not "set") to str

elif message.content.lower() == 'cash app':
    await message.channel.send(
        'Perfect Choice, Please send the amount to this CashApp ' + {cashapp}
        + (message.author.mention))
smoky sinew
#

remove the {}

slate swan
slate swan
#

does anyone specialize in discord.py and can explain why my code isnt working? i swear its right๐Ÿ˜ญ

sick birch
slate swan
slate swan
# sick birch You should post your code along with relevant traceback and why you think it's n...
import discord
from discord.ext import commands
from discord.ext import tasks
from itertools import cycle
import os
import asyncio


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

bot_status = (["/cancelled", "on", "top"])
status = next(iter(bot_status))
activity = discord.Streaming(name=status, url='https://twitch.tv/764')

@tasks.loop(seconds=10)
async def change_status():
    
    
    await client.change_presence(activity=activity)

@client.event
async def on_ready():
    print("/cancelled is online")
    change_status.start()

async def load():
    for filename in os.listdir("./cogs"):
        if filename.endswith(".py"):
            await client.load_extension(f"cogs.{filename[: -3]}")

async def main():
    async with client:
        await load()
        await client.start('token_here')```
sick birch
#

And what's the problem

slate swan
#

when i run it it doesnt run the bot it just stops

#

Because you aren't calling the main function anywhere

#

oh

#

skull long day

#

now i got it working but it wont find my cogs sigh

smoky sinew
#

why even load extensions automatically

#

is it not worth it to type in the extra line

slate swan
mild lava
#

in discord.py, view timeouts are facilitated by the library itself, right?

golden portal
#

just spawns a task and do a sleep at an interval until ends

slate swan
#
import discord
from discord.ext import commands

class Mod(commands.Cog):
    def __init__(self, client):
        self.client = client
    @commands.Cog.listener()
    async def on_ready(self):
        print("Mod.py is ready.")
    
    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def purge(self, ctx, amnt: int):
        await ctx.channel.purge(limit=amnt)
        await ctx.send("purge successful gang")

    

async def setup(client):
    await client.add_cog(Mod(client))``` this is my cog for moderation commands as of right now, when i load the bot it now runs fine, but when i run commands, it gives me an error stating the command name isnt defined.
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 !traceback

โ†[30;1m2023-06-14 01:06:10โ†[0m โ†[31mERROR โ†[0m โ†[35mdiscord.ext.commands.botโ†[0m Ignoring exception in command None
โ†[31mdiscord.ext.commands.errors.CommandNotFound: Command "purge" is not foundโ†[0m !!

#

Do you actually load the cog

fierce crag
#

!warn 858557059868000286 this isn't a place for you to advertise.

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied warning to @silk turtle.

sonic vapor
#

how to make bot online forever

twilit grotto
sonic vapor
slate swan
#

Purchase a VPS
Run your bot there

vale wing
# sonic vapor how

Yeah first you need to get the VPS. The reputable services are listed here: https://www.pythondiscord.com/pages/guides/python-guides/vps-services/

As for free options, you can use amazon AWS free tier, microsoft azure (both last for 1 year) or digitalocean (200$ for 2 months).

I recommend getting a machine with ubuntu OS, then following this guide to setup hosting there https://www.pythondiscord.com/pages/guides/python-guides/docker-hosting-guide/

orchid lagoon
#
from discord.ext import commands

BOT_TOKEN = 'Here'

intents = discord.Intents.default()
intents.typing = False
intents.presences = False

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


@bot.event
async def on_ready():
    print("Bot is online and ready.")
    print(f"Logged in as: {bot.user.name}")
    print(f"User ID: {bot.user.id}")


@bot.command()
async def ping(ctx):
    latency = bot.latency
    await ctx.send(f"Pong! Latency: {latency * 1000:.2f}ms")


bot.run(BOT_TOKEN)

Bot doesnt send any message

polar coyote
orchid lagoon
vocal snow
#

!d discord.Intents.message_content

unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

โ€ข The message was sent by the client

โ€ข The message was sent in direct messages

โ€ข The message mentions the client

This applies to the following events...

polar coyote
slate swan
#

Because it sucks ass if you don't really need all intents, which is 99% of the time the case for bots

slate swan
#

does anyone have any good tips or pointers for a anti nuke in discord.py

vale wing
#

Destroying server?

#

You could like put limit of channels creation per minute or smth

#

I can't really think of anything more effective

#

There are millions of ways to destroy server

vale wing
#
  1. Create infinite channels named "balls"
  2. Delete all channels
  3. Remove all roles
  4. Create infinite roles named "balls" with admin perms and give them to everyone
  5. Invite spam bots that would send "balls" message every second in every channel
#

Only 5 but trust me there are 999995 more definitely

vocal plover
glacial tide
#

I just need how to know how to call the embed being created using the sell command

unkempt canyonBOT
#

examples/views/confirm.py lines 53 to 59

await view.wait()
if view.value is None:
    print('Timed out...')
elif view.value:
    print('Confirmed...')
else:
    print('Cancelled...')```
unkempt canyonBOT
#

examples/views/confirm.py lines 36 to 38

@discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button):
    await interaction.response.send_message('Cancelling', ephemeral=True)```
glacial tide
#

@slate swan did u read my code?

#

i used that rapptz resource

slate swan
#

I did, hence my response

glacial tide
#

m just askin what should i type where these ????? are situated

slate swan
#

Or that

glacial tide
slate swan
#

Do you need to send a new view? No. So remove it

#

Have you defined the embed object? No. So define it

glacial tide
slate swan
#

No.

#

To remove a view, delete view=view it shoudln't be too hard, right?

glacial tide
#

thats good

#

its about the embed

slate swan
#

To define an embed it is

embed = discord.Embed(description="whatever")
#

Just like you did below, shouldn't be too hard as well...

glacial tide
#

I basically want to return the embed generated below ^^

#

not to create a new one

slate swan
#

Then define an attribute in your class and pass that embed to the view class when when creating it in code e.g. view = Sell(embed) and then you can use that embed in the button callback with self.whatever and whatever being the attribute you've created

slate swan
#

No it doesn't, you haven't defined/created the attribute

glacial tide
#

boom lol

slate swan
#

Good you can read

#

OOP is a thing you must know when using libraries like discord.py https://www.w3schools.com/python/python_classes.asp

#

Look at the __init__ function

#

Oops

slate swan
smoky sinew
unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

vale wing
young pendant
smoky sinew
young pendant
#

will that disable @everyone from getting the popup when typing in / ?

young pendant
smoky sinew
#

hmmm i think the check is done locally

#

don't you have to disable the command in the server

slate swan
#

Lets say my bot sends a message when calling a command. This message uses variables like name or index. How could I edit the message text and still have access to those variables inside a View class (when pressing a button)? For example, bot ask if name is equal to index idx, and u have 2 buttons, yes and no. If u press yes, text is changed to f"This {index} is {name}". Inside the ui.View i dont have the variables name and index

young pendant
glad cradle
#

what library are you using?

young pendant
#

from discord import app_commands

glad cradle
#

!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 "discord.app_commands.check"). Therefore, error handlers are not called.

Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
young pendant
wraith wing
#

await ctx.send("Saniye sayฤฑlฤฑyor...", view=View(button2))
^^^^^^^^^^^^^
TypeError: View.init() takes 1 positional argument but 2 were given

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: View.init() takes 1 positional argument but 2 were given

pulsar burrow
#

anybody know what this error means

turbid condor
#

A question I am using mysql so should I make a new connection to the host every time a command is used or just a make a new cursor for the command and close the cursor when the command has been completed?

slate swan
#

Example of view can be found here

#

In this example they create the items in the View subclass which is more readable

slate swan
slate swan
#

go check yourself under examples folder

#

idk what to look for xd

slate swan
#

i saw... ๐Ÿ˜ฆ

#

and do u know by chance how could i do this?

#

save the message in a view then on button click edit it

#

you need to subclass view for it

#

yes, but if the message has variables and the message is like f'variable1: {var1} - variable2: {var2}', how can i use var1 and 2 on the View subclass?

slate swan
#

how do i do that?

#
class MyCustomView(ui.View):
    def __init__(self, var1, var2):
        self.var1 = var1
        self.var2 = var2

    ...


...
var1 = 1
var2 = 2
view = MyCustomView(var1, var2)
.send(f"{var1} {var2}", view=view)


#

oh

#

on the constructor?

#

yes

#

oooh nice, thanks ๐Ÿ˜„

#

keep in mind that when you override the __init__ method you need to call super().__init__()

#

oh true

slate swan
#

One last thing. If i am editing the embed... Should i actually edit it or send a new embed object with same structure?

slate swan
slate swan
#

i dont see any open await commands like its saying,

#

And could u tell me why? Like, is it easier for the bot to edit than send a new one? And if i wanna edit it... I guess it is under interaction.response, but how do i get what do i wanna edit?

#

discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.moderation' raised an error: TypeError: object NoneType can't be used in 'await' expressionโ†[0m

slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
#

do it like this

#


view = ...

view.message = await .send(...)
#

then you have .message varriable in your view

#
โ†[31mTraceback (most recent call last):
  File "C:\Users\fake\dadat\Lol\game\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 947, in _load_from_module_spec
    await setup(self)
TypeError: object NoneType can't be used in 'await' expression

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

Traceback (most recent call last):
  File "C:\Users\notreal\funny\lol\this\Python\Python38\lib\site-packages\discord\client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\notreal\games\bot\bot.py", line 24, in on_ready
    await client.load_extension("cogs.moderation")
  File "C:\Users\not real\stuff\Lol\this\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
    await self._load_from_module_spec(spec, name)
  File "C:\Users\lolol\path\fake\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 952, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.moderation' raised an error: TypeError: object NoneType can't be used in 'await' expressionโ†[0m```
slate swan
#

Well, i dont know exactly what is the best way to edit. There is .edit, .edit_message and .edit_original_response

slate swan
slate swan
#

client.add_cog must be awaited as well

#

!d discord.ext.commands.Bot.add_cog

unkempt canyonBOT
#

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

Adds a โ€œcogโ€ to the bot.

A cog is a class that has its own event listeners and commands.

If the cog is a [`app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group") then it is added to the botโ€™s [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") as well.

Note

Exceptions raised inside a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog")โ€™s [`cog_load()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.cog_load "discord.ext.commands.Cog.cog_load") method will be propagated to the caller...
slate swan
slate swan
#

This is a lower level interface to InteractionMessage.edit() in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.```
#

okay im gonna go fix right noe

#

what does "you do not want to fetch the message and save an HTTP request" mean?

slate swan
#

Okey so, this is what i have now

class Counter(discord.ui.View):
    def __init__(self, name=None, idx=None):
        super().__init__()

    # When pressed, this decrements the number displayed until it hits 0.
    # When it hits 0, the counter button is disabled, and it turns green.
    # note: The name of the function does not matter to the library
    @discord.ui.button(label=str(DENIES), style=discord.ButtonStyle.danger)
    async def button_no(self, interaction: discord.Interaction, button: discord.ui.Button):
        c = int(button.label) or DENIES
        if c - 1 <= 0:
            button.label = 'NO'
            button.style = discord.ButtonStyle.red
            button.disabled = True
            self.remove_item(self.button_yes)
        else:
            button.label = str(c - 1)

        # Make sure to update the message with our updated selves
        await interaction.response.edit_message(view=self)```
The last line is that updates the view, i believe. Since i only change the label of the button "no". But i believe the message itself is on interaction.response, no?
#

i dont have any self.message

#

tbh, im a bit lost between Interaction.message and .response

slate swan
#

what is a better practice:

#
@client.command()
async def s(ctx):
    embed1 = discord.Embed(title="Embed 1", description="This is the first embed.")
    embed2 = discord.Embed(title="Embed 2", description="This is the second embed.")
    embed3 = discord.Embed(title="Embed 3", description="This is the third embed.")

    embeds = [embed1, embed2, embed3]

    await ctx.send(embeds=embeds)
    await ctx.send('-----------------')
    await ctx.send(embed=embed1)
    await ctx.send(embed=embed2)
    await ctx.send(embed=embed3)```
#

sending multiple embeds on the same message, or different msgs?

#

Multiple in one, you won't unnecessarily hit rate limits faster by making multiple API requests

slate swan
#

may i ask why?

#

cause each ctx.send is an api call

#

so you either call api once or 3 times

#

ah

#

i see, thanks ๐Ÿ˜„

#

thats why i have to interaction.message.embeds[0]

sick coyote
#

yo can someone help me, for some reason my bot goes offline, i looked in the logs nothing. its the second time now

#

im using nextcord

young pendant
#

So, i have a python script here:
https://paste.pythondiscord.com/atanenisub

at line 126 I have a context menu named "report_message"

The bot sends a message in a predifined channel

I want the bot to include 2 buttons and a dropdown menu below the embed

Buttons: Go to message (link of reported message) / claim

Dropdown: Options: ban, tempban, mute, tempmute, warn, verbal warn, nothing

When the button "CLAIM" has been clicked, it should change color from blue to green and say "claimed by (user)"

When I chose an action from the dropdown (only one should be chosen), it should say what action has been chosen

twilit grotto
#
class Moderation(commands.Cog):
    def __init__(self, client):
        self.client = client

    @nextcord.slash_command(name="moderation", dm_permission=False)
    @commands.guild_only()
    async def moderation_group(self, interaction: Interaction):
        await Checks._defer(self, interaction)
        return await interaction.followup.send("This shouldn't be able to be ran by itself, but if you're seeing this, good job!.", ephemeral=True)
    
    @moderation_group.subcommand(name="ban", description="Allows you to ban a member for a certain reason, and time (minutes) (both optional)")
    @commands.guild_only()
    @commands.has_permissions(ban_members=True)
    async def ban_cmd(self, interaction: Interaction, member: nextcord.Member, reason: str = None, minutes: int = 10):
        await Checks._defer(self, interaction)
    
    @moderation_group.subcommand(name="kick", description="Allows you to kick a member for a certain reason (optional)")
    @commands.guild_only()
    @commands.has_permissions(kick_members=True)
    async def kick_cmd(self, interaction: Interaction):
        await Checks._defer(self, interaction)
    
    @commands.Cog.listener()
    async def on_ready(self):
        print(f"{self.__class__.__name__} loaded.")
    
    @commands.Cog.listener()
    async def on_slash_command_error(self, ctx: commands.Context, error):
        if isinstance(error, nextcord.errors.MissingPermissions):
            await ctx.send("You don't have the required permissions to use this command.")

def setup(client: commands.Bot):
    client.add_cog(Moderation(client))

```is there any reason this cog (using nextcord) doesnt actually check if the user has permissions upon running ban or kick? im kinda confused. lmao
potent spear
twilit grotto
#

which is confusing me completely.

potent spear
#

I don't use nextcord, so I can't really help with those slash commands there

keen swan
#

Hey hey, I have a (hopefully not too complicated) question
I'm trying to create a button that opens a website when it gets pressed while subclassing discord.ui.View and i'm not sure where to specify the URL that is supposed to open

@discord.ui.button(label="Find websites", emoji="๐Ÿ”",style=discord.ButtonStyle.link)
async def find_websites_callback(self, interaction: discord.Interaction, button: discord.ui.Button):
  print("hi")
upbeat gust
#

in the view init

b = ui.Button(..., url = "xyz")
self.add_item(b)```
slate swan
#

why when editing an embed message with an image attached the image goes outside the embed but stays inside too? the image is dupped

keen swan
young pendant
gilded kraken
#

how do i make multiple enimies in pygame

upbeat gust
gilded kraken
#

why is it bad

upbeat gust
# gilded kraken why is it bad

what's an enemy? wdym make? it gives us 0 info about what you're trying to do and we have to waste time guessing what you mean

young pendant
snow coral
#

so i have my discord bot save data to a file, but how can i make it so it doesnt keep overriding line 1, and go to the next line

sonic vapor
#

I need a patner for making a bot

slate swan
#
DiscordAPIError[50001]: Missing Access
    at handleErrors (C:\Users\user\OneDrive\Documents\Discord bot\node_modules\@discordjs\rest\dist\index.js:640:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async SequentialHandler.runRequest (C:\Users\user\OneDrive\Documents\Discord bot\node_modules\@discordjs\rest\dist\index.js:1021:23)
    at async SequentialHandler.queueRequest (C:\Users\user\OneDrive\Documents\Discord bot\node_modules\@discordjs\rest\dist\index.js:862:14)
    at async REST.request (C:\Users\user\OneDrive\Documents\Discord bot\node_modules\@discordjs\rest\dist\index.js:1387:22) {
  requestBody: {
    files: undefined,
    json: [
      [Object], [Object],
      [Object], [Object],
      [Object], [Object],
      [Object], [Object],
      [Object], [Object]
    ]
  },
  rawError: { message: 'Missing Access', code: 50001 },
  code: 50001,
  status: 403,
  method: 'PUT',
  url: 'https://discord.com/api/v10/applications/1107421055431225346/guilds/1107420871393542173/commands'
}```
#

i gave it commands.applications

#

and allat and it still doesnt work?

twilit grotto
slate swan
twilit grotto
slate swan
#

whoops

#

got confused

#

thought this was a different server, i was using ctrl + k

snow coral
#

so i have my bot read a txt file and send it, but would it be able to print a certain part? like for example:

#

this is what sends it

twilit grotto
snow coral
#

and doesnt just send the whole thing

twilit grotto
#

split the data, and extract the data you need to send

naive briar
#

To be honest, just use JSON at this point

twilit grotto
snow coral
twilit grotto
#

yeah JSON in that case would be so much better & so much easier lmao

lone robin
#

Quick question,

Do any of y'all use Rasberry pi for bot hosting ?
& Can it run intricate and complex bots with no issue ? "8gb ver"

slate swan
#

does anyone have an idea of how to create a keep alive.py file so i can keep my bot running using uptimereboot

frail kettle
#

I havent created discord bots in a year I imagine many things have changed especially with discord switching over to slash commands is there anywhere I can learn it again. I dont really want to read through the docs so if anyone has any other methods please share them

frail kettle
#

thank you cheers!!

slate swan
#

@bot.event
async def on_message(message, self, msg):

Blacklist= ["discord.gg", ".com"]
for black in Blacklist:
        if black.lower() in msg.content.lower():
            await msg.delete()
            await msg.channel.send(f"WATCH YOUR TONE")
#

Why doesn't my code work

#
@client.event
async def on_member_join(member):
    message = f"Wasg {member.mention} Thanks for joining the community gang"
    print(message)
    
  
    embed = discord.Embed(title="New Member Joined",
    description=message, color=discord.Color.random())
    
    embed.set_thumbnail(url=member.avatar_url)
    
    embed.add_field(name="Join Date",       
    value=member.joined_at.strftime("%Y-%m-%d %H:%M:%S"), inline=False)
    
  
    channel = client.get_channel(channel.id)
    
    await channel.send(embed=embed)``` 

```AttributeError: 'Member' object has no attribute 'avatar_url'```
tired notch
#

it got changed i think its member.avatar.url now

slate swan
#

ohh ok thank you

tired notch
#

the one i use is display_avatar

tired notch
slate swan
tired notch
#

should already be doing that

unkempt canyonBOT
#

You are not allowed to use that command.

vale wing
#

I doubt if "free robux" in msg.content.lower() would work ๐Ÿง

naive briar
#

Ask someone if they're a scammer brainmon

shrewd apex
vale wing
shrewd apex
#

reverse psychology

vale wing
shrewd apex
#

oof

slate swan
#

Question, so I have a curse word blocker, when the word gets deleted I want it to send to a channel saying โ€œBad word detected and what word it isโ€ how can I code that

twilit grotto
twilit grotto
north kiln
#

why not just use automod

cyan quarry
#
    client.application._patch(data.application);
                       ^

TypeError: client.application._patch is not a function
    at module.exports [as READY] (/Users/roopa/Desktop/projects/LLbot/node_modules/discord.js/src/client/websocket/handlers/READY.js:21:24)
    at WebSocketManager.handlePacket (/Users/roopa/Desktop/projects/LLbot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:354:31)
    at WebSocketManager.<anonymous> (/Users/roopa/Desktop/projects/LLbot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:238:12)
    at WebSocketManager.emit (/Users/roopa/Desktop/projects/LLbot/node_modules/@vladfrangu/async_event_emitter/dist/index.js:282:31)
    at WebSocketShard.<anonymous> (/Users/roopa/Desktop/projects/LLbot/node_modules/@discordjs/ws/dist/index.js:1103:51)
    at WebSocketShard.emit (/Users/roopa/Desktop/projects/LLbot/node_modules/@vladfrangu/async_event_emitter/dist/index.js:282:31)
    at WebSocketShard.onMessage (/Users/roopa/Desktop/projects/LLbot/node_modules/@discordjs/ws/dist/index.js:938:14)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Node.js v20.2.0

๐Ÿ’€ internal error ๐Ÿ’€

shrewd apex
#

anyways ._patch is not a callable

slate swan
#

!src

unkempt canyonBOT
cyan quarry
#

mb mb

slate swan
#

in python discord server

#

crying in python

vale wing
#

!pypi js2py

unkempt canyonBOT
#

JavaScript to Python Translator & JavaScript interpreter written in 100% pure Python.

cyan quarry
vale wing
#

Maybe try javascript server

#

Or whatever there is

cyan quarry
#

k lol

fallen meadow
#

Does anyone know if there is a code that makes it plausibel for clikable phone Numbers on discord

vale wing
#

๐Ÿง

fallen meadow
#

Its like the same when you look up a company on Google and it shows a number you can click and it will Ask if you wanna call it

soft fjord
#

Can anyone help me with this ?
I want to make command which will help bot owner to invoke command behalf of other users
Here is the code I tried but does not work as i expected --

    @commands.command(name="dbg")
    @commands.is_owner()
    async def debug_command(self, ctx, user: Optional[commands.MemberConverter], command: str = ""):
        if not command:
            await ctx.send(":exclamation: Please provide a command to execute.")
            return

        if user is None:
            user = ctx.author

        invoked_command = self.bot.get_command(command)
        if invoked_command is None:
            await ctx.send(f":exclamation: Invalid command: {command}")
            return

        ctx.message.author = user
        await self.bot.invoke(ctx)
soft fjord
#

Yaa

slate swan
#

.

#

I got banned from the other serv cause they thought I was raiding jt

#

So here I am

cyan quarry
#

lol

slate swan
#

but my message got removed โ˜ ๏ธ

cyan quarry
slate swan
#

oh

#

okay

cyan quarry
slate swan
cyan quarry
#

i'm on macbook with OG discord app ๐Ÿ’€

slate swan
cyan quarry
slate swan
cyan quarry
shrewd apex
slate swan
shrewd apex
slate swan
shrewd apex
slate swan
#

main.py like a civil and respectable man

#

main.txt GIGACHAD

#

Bot.py users are heathens who need to be burned

shrewd apex
#

hmm my subclassed bot is in bot.py but i import and run it in __main__.py

slate swan
#

eval(open("main.txt", "r", encoding="utf-8")) GIGACHAD GIGACHAD GIGACHAD GIGACHAD GIGACHAD

slate swan
#

Would suggest being careful

slate swan
shrewd apex
#

seemed appropriate

slate swan
shrewd apex
#

need nitro ๐Ÿฅน

shrewd apex
slate swan
#

you are not blue anymore

shrewd apex
#

yessir

#

i am plain white

slate swan
#

that means you are casual now

languid jungle
# cyan quarry

@slate swan I don't think JS Hub is a javascript discord

#

nvm, it is

#

the /js vanity used to be owned by a discord server unrelated to javascript

slate swan
#

i have it under my programming discords folder so it has to be about js

languid jungle
#

it's not related to javascript

#

we've that discord server blacklisted for this very reason

slate swan
languid jungle
#

haha

slate swan
cosmic karma
rugged shadow
glad cradle
#

btw __main__.py is better than main.py if your project is structured like a package

cyan quarry
#

tbh .js version is easier

#

ngl ๐Ÿ’€

slate swan
vale wing
#

Without IDE*

pliant gulch
#

main.py? Nah poetry run bot

slate swan
#

no poetry run python -m bot

pliant gulch
#

No

#

You can setup scripts in poetry with an entry point

slate swan
#

i know you can

pliant gulch
#

Oh that's what you meant

vocal plover
#

my preferred way of running bots now is to not run bots KEKW

pliant gulch
#

exactly

#

bot dev in 2023?

#

crazy

slate swan
#
ENTRYPOINT ["poetry", "run"]
CMD ["python", "-m", "bot"]
pliant gulch
#

docker!?

slate swan
#

obviously

vocal plover
#

docker my beloved

pliant gulch
#

I have never had to use docker for any of my bots pepesweat

slate swan
#

for me its just easier to set up everything in docker compose

#

also its easier when moving to VPS

pliant gulch
#

ic, usually I just do everything in poetry, move it over from git and just poetry install

vocal plover
#

I use docker for bots mostly because when you've written like 1 python dockerfile it suddenly becomes unbelievably easy to deploy 99% of bots

pliant gulch
#

I usually have a schema.sql too so setting up the database is no problem

slate swan
#

i just copy paste the dockerfiles

#

imagine deploying bots

lost dove
#

how can i use jishaku??

slate swan
lost dove
slate swan
lost dove
#

i did

slate swan
#

you need to use the one using async/await syntax

lost dove
#

if i do without await it wont work?

slate swan
#

i belive it will throw exception

lost dove
#

lemme try

#

works

#

ty

slate swan
#

can u forbide all users except the one who used a command to interact with a view?

#

Yes

#

how? is there a fancy way or u just check who reacted?

thin raft
slate swan
#

so for the rest of users buttons will be enabled?

thin raft
#

you can't disable buttons for a single users

#

you would need to check who interacted and do something if x or y

slate swan
#

okey

thin raft
#

or better way

austere prairie
slate swan
#

so i guess it would be interaction.message.client?

unkempt canyonBOT
#

class discord.Interaction```
Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

New in version 2.0.
austere prairie
# austere prairie https://github.com/python-discord/bot/blob/main/bot/exts/info/subscribe.py#L63-L...

This is the essential part:

class MyView(discord.ui.View):
    def __init__(self, owner):
        ...
        self.interaction_owner = owner

    async def interaction_check(self, interaction):
        if interaction.user != self.interaction_owner:
            # You can do something else here, this shows an ephemeral message to the user
            await interaction.response.send_message(
                "This is someone else's button",
                ephemeral=True,
            )
            return False
        return True
#

@slate swan

slate swan
#

and where do i pass owner?

austere prairie
#

when you instantiate the view

slate swan
#

when creating the view

#

yeah i mean, what should owner be?

austere prairie
#

the person who can click the button

slate swan
#

ctx.send(..., view=View(what))

#

the user/member object

austere prairie
#

probably ctx.author or similar

slate swan
slate swan
#

one thing i dont understand what i did

#
client = cmds.Bot(command_prefix=BOT_PREFIX, help_command=None,
                  activity=Game(name=f'{BOT_PREFIX}help'), intents=intents)

client.channels_ids = {}```
#

By doing this, im giving the bot an attribute called channels_ids which is a dictionary?

#

can i actually do that???

vocal snow
#

yes

#

it's an unslotted class

slate swan
#

what does unslotted mean?

vocal snow
#

it doesn't use _slots_, which is a sequence of strings that defines what attributes an object of that class can have

slate swan
#

that you can add your own attributes from the outside

#

!botvar

unkempt canyonBOT
#
Bot variables

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

slate swan
#

oooh

#

i see. Thats cool

slate swan
#

any idea how to make a server info command for a bot in discord.py? been stumped for hours...

turbid condor
#

What type of info u want it to display??

slate swan
#

!d discord.Guild Take a look at the list of attributes here

unkempt canyonBOT
#

class discord.Guild```
Represents a Discord guild.

This is referred to as a โ€œserverโ€ in the official Discord UI.

x == y Checks if two guilds are equal.

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

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

str(x) Returns the guildโ€™s name.
turbid condor
slate swan
#

editing a msg vs deleting and sending new are the same amout of api calls?

turbid condor
#

Aren't they 3 different processes?

vocal snow
#

because each has it's own endpoint

pulsar burrow
slate swan
#

can i make a bot with discord.py that gives a role and then removes it 10 minutes later?

slate swan
austere prairie
#

What do you want

slate swan
#

A hi?

#

Bro you don't remember?

austere prairie
#

Hm?

thin raft
#

lol

low forum
#

Hello community, somebody can help me with pywhatkit? or teach me another form to send whatsapp messages from python.

slate swan
shrewd vapor
#

Hi, i search for remove timeout with command unmute you can help me please ?

sick birch
#

!d discord.Member.timeout

unkempt canyonBOT
#

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

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

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

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

Yes

slate swan
#

yo
does anyone know how i can code a vouch command (discord bot) im not rly sure how to start/what to do

slate swan
#

also You can't ask such a vague question and expect code cause literally you didn't specify alot of stuff

#

๐Ÿ‘

shrewd vapor
#

File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 842, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/otrobot.py", line 712, in unmute
await member.timeout(duration = None, reason = None)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Member.timeout() got an unexpected keyword argument 'duration'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 856, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'unmute' raised an exception: TypeError: Member.timeout() got an unexpected keyword argument 'duration'

slate swan
#

Step 0: Take the time to learn Python and OOP

unkempt canyonBOT
#

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

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

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

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

you need to do that on instance

#

As you can see, no duration only until

#

not the class

shrewd vapor
#

Until don't work

#

I don't understand for remove timeout

slate swan
#

Pass until as None, more simple than that is hard

shrewd vapor
# slate swan Pass `until` as `None`, more simple than that is hard

Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 842, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/otrobot.py", line 712, in unmute
await member.timeout(until = None, reason = None)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Member.timeout() got some positional-only arguments passed as keyword arguments: 'until'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 856, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'unmute' raised an exception: TypeError: Member.timeout() got some positional-only arguments passed as keyword arguments: 'until'

slate swan
#

You already got told above what's the issue

tidal dock
#

hello

shrewd vapor
#

Sry but i can't do it

fathom tundra
#

eyo whats the best langauge for

#

discord

#

bots*

glad cradle
#

assembly

sick birch
#

Personal preference

fathom tundra
#

hm whats the easyiest

#

i can python and c# an java

#

whats the best

glad cradle
fathom tundra
#

not best what do you recommend

#

hm#

slate swan
#

The one you know the most

#

You choose, we don't

fathom tundra
#

okay

slate swan
slate swan
fathom tundra
shrewd vapor
#
@bot.tree.command(name="unmute", description="Unmute a member")
@commands.guild_only()
async def unmute(interaction, member: discord.Member):
    await interaction.response.defer()
    if not interaction.user.guild_permissions.kick_members:
        await interaction.followup.send(f"You are not authorized to use this command {interaction.user.mention}")
        return
    await member.timeout(until = None, reason = None)
    await interaction.followup.send(f'{member.mention} has been unmuted')```
slate swan
#

Good thing people know the difference between kwarg and positional args

#

it tells you that until is positional only and you passed it as keyword

shrewd vapor
#

sry if i don't understand the doc and all your message, english is not my native langage

slate swan
#

English doesn't matter here, it's python knowledge you're lacking of

fathom tundra
#

okay

#

thanks