#discord-bots

1 messages · Page 174 of 1

abstract owl
#

ayee ty so much bro

sick birch
abstract owl
#

also one more doubt i have a configuration bot that basically works on the json file and a main bot which works on everything and everytime i like use a command of configuration bot it just throws an error in the main bot saying that xyz variable is Refrenved before assignment. The reason being for a split second the data inside json file is deleted and a new data is dumped. Any way to overcome it?

sick birch
desert heart
#

I think the library is called intersphinx. Refer to the @unkempt canyon source code to see how it was used. I don't know the details well.

abstract owl
real badger
#

I get the error:
AttributeError: 'Guild' object has no attribute 'category'
What do I do?

fading marlin
#

perhaps you meant categories?

cloud dawn
#

Does seems like he wants a specific one.

real badger
sick birch
real badger
#

How do I create a channel in a certain category?

cedar estuary
#

still gets the bots author if i do it like this

crimson mauve
crimson mauve
slate swan
#

hey where could I move this return statement at?

feral frost
#

Code

            cursor.execute(f"SELECT user FROM liked WHERE id = {user1.id}")
                result = cursor.fetchone()

                if result is None:
                    sql = ("INSERT INTO liked(id, user) VALUES(?, ?)")
                    val = (user2.id, user2)

                    cursor.execute(sql, val)
                    db.commit()

                elif result is not None:
                    query = ("DELETE from liked WHERE user = ?")
                    params = [user2.id]

                    cursor.execute(query, params)
                    db.commit()

Error

cursor.execute(sql, val)
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.```
#

anyone knows what i need to do ?

cedar estuary
crimson mauve
#

At this point it's up to you where to store the ID, I would pick footer because it's the simplest right now. Not unless you want to start learning databases.

crimson mauve
#

With that there it's blocking all the code under it from running.

cedar estuary
mental hollow
#

🤨

crimson mauve
#

lol

mental hollow
#

message.embeds[0].footer id assume

crimson mauve
#

!d discord.Message.embeds

unkempt canyonBOT
mental hollow
#

ya

crimson mauve
#

there we go

young dagger
#

How can I fix this?
discord.ext.commands.errors.MemberNotFound: Member "29455219532952935" not found.

@client.command()
async def warn(ctx, member: discord.Member = None, *, reason: str=None):

    if reason is None:
        await ctx.send("You must provide a reason for the warning.")
        return

    if member is None:
        await ctx.send("Could not find that member. Please try again.")
        return```
real badger
#

How do I delete a category and everything in it in a button?

umbral mesa
#

If you want to get an attachment like image or video ect from a message try "ctx.message.attachments[0].url"

feral frost
real badger
#

whats the pastebin link?

feral frost
#

huh ?

real badger
#

for the python discord whats the pastebin

feral frost
#

for python discord ?

crimson mauve
#

I'll figure it out some day

real badger
#

!pastebin

unkempt canyonBOT
#

Pasting large amounts of code

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

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

crimson mauve
#

I was almost there

real badger
#

xd

feral frost
#

i didnt understand

real badger
crimson mauve
#

What you are asking for is not really what we do in this channel.

feral frost
#

but it is about discord bots so it can be both

crimson mauve
#

What did they have to say?

feral frost
#

me ?

crimson mauve
feral frost
#

well to late

crimson mauve
#

Good luck then

feral frost
#

thanks

real badger
#

are you able to help me based on the code i sent?

feral frost
#

sure

#

ill have a look

crimson mauve
feral frost
#

with a button ? you said

real badger
#

yeah

#

it would have to happen in class suite_close

crimson mauve
#

looking over it

#

try

   @discord.ui.button(label = "Create a Suite", style = discord.ButtonStyle.blurple, custom_id = "PlasmaBotsuite_button")
    async def ticket(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.defer()
        suiteCategory = utils.get(interaction.guild.categories, name = f"{interaction.user.name}'s Suite")
real badger
#

how do I delete the category? Because it is not a channel. Also how do I delete the voice channel?

dull basalt
#
import discord
from discord.ext import commands
from discord import app_commands

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

@bot.event
async def on_ready():
    print(f"We have logged in!")
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command")
    except Exception as e:
        print(e)

@bot.tree.command(name="hello", description="say hello")
async def hello(interaction: discord.Interaction):
    await interaction.response.send_message(f"Hello {interaction.user.mention}!")
    
bot.run(12345)# I know that is not the bot token. ````






\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 672, in connect
    raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

#

does anyone know how to fix this

crimson mauve
unkempt canyonBOT
#

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

Deletes 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.
tawny junco
dull basalt
#

i can't find it

real badger
#

That works! How do I search for the voice channel because the voice channel is named General and I am worried about deleting other voice channels named General?@crimson mauve

dull basalt
#

do u see it

#

@tawny junco this is the thing of perms and scopes i can give it ^

tawny junco
#

I found it

#

Go to the bot tab and it should be right there

dull basalt
#

it is already enabled

#

i am rly confused bc it is checked it has admin perms and has no errors and it still is broken

tawny junco
#

Try this

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
dull basalt
#

like this?

tawny junco
#

Yes. Does it work

dull basalt
#

no same error

young dagger
#

How do I add a message if memebr is not found?
discord.ext.commands.errors.MemberNotFound: Member "29455219532952935" not found.

@client.command()
async def warn(ctx, member: discord.Member = None, *, reason: str=None):

    if reason is None:
        await ctx.send("You must provide a reason for the warning.")
        return

    if member is None:
        await ctx.send("Could not find that member. Please try again.")
        return```
tawny junco
dull basalt
#

ok should i just ask around to see if anyone knows

real badger
#

How many commands do you have on your bot @dull basalt

dull basalt
#

1 bc i am trying to find the issue

crimson mauve
#

!d discord.Client.get_channel

unkempt canyonBOT
#

get_channel(id, /)```
Returns a channel or thread with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
primal token
unkempt canyonBOT
#

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

A local error handler is an [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event limited to a single command. However, the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") is still invoked afterwards as the catch-all.

Changed in version 2.0: `coro` parameter is now positional-only.
primal token
#

also your annotations arent correct

real badger
young dagger
real badger
crimson mauve
dull basalt
#

lighgeb it is on slash commands

real badger
#

why did you define a command prefix

primal token
# young dagger What do you mean?

when adding default values you must provide the type of the default value if its not the same as the one being expected

TL;DR you must be explicit with default values

e.g

# Wrong
def foo(bar: Bar = None) -> None:
    ...


# Correct 
def foo(bar: Bar | None = None) -> None:
    ...
young dagger
crimson mauve
primal token
real badger
dull basalt
#

@real badger wdym

real badger
#

@dull basalt wdym wdym

dull basalt
#

oh

#

i see

#

do i not need that

crimson mauve
#

!d discord.utils.get

unkempt canyonBOT
#

discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find "discord.utils.find").

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.

If nothing is found that matches the attributes passed, then `None` is returned.

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

Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.11)")s...
real badger
young dagger
desert heart
#

Because when an argument to a command is invalid, discord.py will not execute the code in the command - it will raise an error before it gets to that point.

slate swan
#

How can I make my bot play song from youtube with youtube_dl ?

crimson mauve
slate swan
#

I just have !play command and next to it I add the youtube url and then I want my bot to play the video

crimson mauve
#

youtube_dl
Command-line program to download videos from YouTube.com and other video sites

Hmmmmm

unkempt canyonBOT
#

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

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

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

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

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

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

We won't help with projects that breach terms of service here, sorry

slate swan
#

Ok is there another way for doing the thing I want?

desert heart
#

Find a service that allows you to use their content in such way. Or play media files that are stored locally.

shrewd apex
#

if u are just practicing u could use anime and movie websites

slate swan
#

if i have a users authorid in a variable called id so how can i send direct messages to the player using the id variable?

#

await message.id.send

#

does not work, dunno if it's even supposed to work

sick birch
ionic garden
sick birch
#

Checking for errors should be pretty fast

ionic garden
#

alr cool

ionic garden
#

not sure if this is against the spirit of async in & of itself, but i want the bot to print out when it's finished syncing

#
        print("Syncing commands globally...")
        await bot.tree.sync()
        print("Synced commands!")
#

however, this obviously doesn't work

pulsar kettle
#

Kick error does not get bot to send the missing perms message, instead the error just shows in the terminal

@bot.tree.command(name='kick', description='Kicks a member from the server')
@has_permissions(kick_members=True)
async def kick(interaction: discord.Interaction, member: discord.Member, reason: str=None):
    guild = interaction.guild
    await member.send(f"You have been kicked from: ***{guild.name}*** | {reason}")
    await member.kick(reason=reason)
    embed = discord.Embed(title=(f'***{member} has been kicked*** | {reason}'), color=0xf6ff00)
    await interaction.response.send_message(embed=embed)

@bot.listen()
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(":redTick: You don't have permission to use this command!")
    else:
        raise error```
slate swan
#

Hey

#

for some reason

#

my welcome message don't work

#

and it does not have a error

#

when a member joins

#
async def dm_all(ctx, *, message = None):
        if message != None:
                members = ctx.guild.members
for member in members:
        try:
                await member.send(message)
except:
        pass
else:
        await ctx.send("Please provide an message!")``` I can't seem to figure out where i messed up on the indentation. error states: ```  File "/root/roof.py", line 30
    except:
IndentationError: unexpected unindent``` help.
flat marsh
#

hello i created a bot

#

and when i write in my server i get blank strings

#

printed out

#

not the actual messages

#

If anyone is up to help, it would be appreaciated, im up at 1am trying to figure this issue out for 3hrs now

slate swan
desert heart
#

Also, don't use except:. Catch the actual exceptions you expect to be raised.

#

At a minimum use except Exception:, but even then you should try to be more specific

sick birch
sick birch
ionic garden
sick birch
#

But did it sync?

ionic garden
#

wait uh dumb question

#

when await is called, it does not wait for it to finish right? does it like start a new process & move on or smth?

pulsar kettle
sick birch
flat marsh
#

Would anyone know why printing message.content returns an empty string aka an empty line is printed everytime i write something in my server with the bot in it

sick birch
#

But await does await for the task to finish
That's the whole point

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.

ionic garden
sick birch
#

hard to tell since I don't have context as to what function it's in

#

on_ready, maybe? setup_hook perhaps

pulsar kettle
flat marsh
flat marsh
sick birch
sick birch
#

You need to specify which intents you want

#

message_content is the one that gives you the content to the message

flat marsh
#

Ive enabled message content in the discord portal website so i dont know if its a problem

sick birch
#

Have you enabled it in your code as well?

flat marsh
#

No

sick birch
#

Do that as well

flat marsh
#

How could i do that, im quite new to this

sick birch
flat marsh
#

Kk

#

So basically i have to make the intents into code, alr will do and update u in a minute

pulsar kettle
#

I'll keep experimenting

flat marsh
#

THANK YOU SO MUCH!!!

#

I can finally go sleep now

#

Tmrw is school 💀

sick birch
#

Good luck!

slate swan
#

hey @shrewd apex , i'm taking another look at ur pagimation and got a question.

you have assert isinstance(items, list) so if I define list as a class elsewhere in the code, whatever data is in the list, it can return that as items then right?

sick birch
pulsar kettle
rare echo
#

"test" , "success", "called"

sick birch
#

We just want to see if the function is being called at all

primal token
#

I usually just print 1 lol

sick birch
#

works ¯_(ツ)_/¯

primal token
pulsar kettle
#

So like this?:

@kick.error
async def kick_error(ctx, error):
    if isinstance(error, MissingPermissions):
        await ctx.send(":redTick: You don't have permission to use this command!")
        print("success")
    else:
        raise error```
primal token
#

just after the function definition

pulsar kettle
#
Success
success
Task exception was never retrieved```
#

It prints it twice

sick birch
shut elk
#

oi, can anyone help me with my bot, i posted in python help

pulsar kettle
pulsar kettle
#

Is it not a missing perms thing?

sick birch
#

The missing permission error is wrapped inside a CommandInvokeError

#
@kick.error
async def kick_error(ctx, error):
  error = error.original if isinstance(error, app_commands.CommandInvokeError) else original
  ...
#

This will unwrap the nested error from out the CommandInvokeError container

pulsar kettle
golden portal
#

tbh, should just use getattr, since there are multiple error other than CommandInvokeError that wraps the error

sick birch
#

Yeah you'd have to import it

#

getattr is a better approach, yeah

#
error = getattr(error, "original", error)
#

@pulsar kettle use this instead

pulsar kettle
#

Yes it works! Tysm guys <3

#

Can I just copy and paste that for every command too?

sick birch
#

A global error handler would probably be better then

sick birch
pulsar kettle
#

Aight, I’ll try it out 👍

slate swan
#

can someone help it keeps saying TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict'

subtle jolt
#

how do i delete an application command? No matter what I try, i get every status code but 204

civic fractal
#

!e py non_integer_value = {"key": "value"} as_an_integer = int(non_integer_value)

unkempt canyonBOT
#

@civic fractal :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | TypeError: int() argument must be a string, a bytes-like object or a real number, not 'dict'
lament depotBOT
#
**Status: 204**
sick birch
#

204 is not bad

clear elm
#

does anyonne know how to make a timed mute command? i have a mute command, i just wanna make it so you can control how long they're muted for

@client.command(description="Mutes the specified user.")
@commands.has_permissions(timeout_members=True)
async def mute(ctx, member: discord.Member, *, reason=None):
    guild = ctx.guild
    mutedRole = discord.utils.get(guild.roles, name="Muted")

    if not mutedRole:
        mutedRole = await guild.create_role(name="Muted")

        for channel in guild.channels:
            await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=False)

    await member.add_roles(mutedRole, reason=reason)
    await ctx.send(f"Muted {member.mention} for reason {reason}")
    await member.send(f"You were muted in the server {guild.name} for {reason}")```
subtle jolt
# sick birch 204 is not bad

yeah thats what im trying to get..
is this the right code?

import requests
from btoken import TOKEN


url = 'https://discord.com/api/applications/903765373181112360/commands/1061192774742966342'

headers = {
    'Authorization': f'Bearer {TOKEN}'
}

response = requests.delete(url, headers=headers)```
sick birch
#

You're registering slash commands by hand?

subtle jolt
subtle jolt
#

if this counts as syncing

class MyClient(discord.Client):
    def __init__(self, *, intents: discord.Intents):
        super().__init__(intents=intents)
        self.tree = app_commands.CommandTree(self)
    async def setup_hook(self):
        self.tree.copy_global_to(guild=MY_GUILD)
        await self.tree.sync(guild=MY_GUILD)```
#

do i need to make it global

slate swan
#

what's super() for?

#

*general question

candid jacinth
#

I have a working GPT chatbot and im looking for some assistane 1. Use our current chatGPT bot build a canned response chatbot on top of it that uses a database for responses. 2. Design and implement two databases: --A "canned" database for storing previous questions and answers that have been asked at least three times. --A "live" database for storing current questions and answers that have not yet been canned. 3. Write code to interface with the GPT API and the Discord bot. When a message is received: --Check the "canned" database for a matching question. --If a matching question is found, choose one of the previous responses at random (with a 1/3 chance for each) and send it to the Discord server. --If a matching question is not found, submit the question to the GPT API and save the question and answer to the "live" database. 4. Implement an accuracy system using difflib. If a question is similar (e.g., 95% similar) to a previous canned question, choose the corresponding answer for the most similar question. 5. Create a separate process that sorts through the "live" database and populates the "canned" database with any questions that have been asked at least three times. 6. As the "canned" database grows, consider lowering the temperature and max_token values and potentially using a different model such as Curie to improve the chatbot's responses. Overall, the goal of this chatbot is to create a community database of questions and answers that can be used by future developers to reduce token costs by avoiding unnecessary API calls. The chatbot will save on token costs by using previously asked questions and answers from the "canned" database when possible, while still providing a sense of randomness and organic conversation by choosing responses at random. As the "canned" database grows, the chatbot's responses will become more cost-effective.

slate swan
# slate swan what's `super()` for?

it refers to the main instance of your subclass, for example ```py
class Hello(discord.Client):
def run(self) -> None:
# "i overrided this method"
super().run("...")

`super()` here would be the original discord.Client() instance that Hello wraps
#

ohhhh

#

ty

civic fractal
#

the solution is to not do that

civic fractal
#

the way to "fix" it is to not try and divide zero by zero

shrewd apex
slate swan
# shrewd apex no lol i have multiple paginators handed down so thats for typehint purposes for...

then i'm lost on how I can use it 😢 i cant just add this data and have a command include the embed i'm guessing?

        for member in ctx.guild.members:
            self.DataPost[f"Member: {member.name} Member.ID {member.id}\n"] = None

        for role in ctx.guild.roles:
            self.DataPost[f"Role: {role.name} Role.ID {role.id}\n"] = None

        for category in ctx.guild.categories:
            self.DataPost[f"Category: {category.name} Category.ID {category.id}\n"] = None

        for channel in ctx.guild.channels:
            self.DataPost[f"Channel: {channel.name} Channel.ID {channel.id}\n"] = None
or
        list = []
        for member in ctx.guild.members:
            list.append((member.name, member.id))
        for role in ctx.guild.roles:
            list.append((role.name, role.id))
        for category in ctx.guild.categories:
            list.append((category.name, category.id))
        for channel in ctx.guild.channels:
            list.append((channel.name, channel.id))

cause everything i've tried, keeps giving errors unless i'm supposed to just import this into another .py, idk what else to try ;.;

ionic garden
#

is there a way to hide a bot cog from the general public? like it won't even show up in the autocomplete in non-authorized servers?

shut elk
#

You can ping me here and tell me if u know, thx

fading marlin
#

You're not responding fast enough to the interaction

real badger
#

!pastebin

unkempt canyonBOT
#

Pasting large amounts of code

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

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

shut elk
#

click on the link

shut elk
fading marlin
#

either defer or respond faster 🤷

shut elk
#

So would I have to put it at the start of the function?

shut elk
#

Because I'm trying to edit msg with a view

#

and I don't think you can followup edit msg unless there is

fading marlin
#

you can edit_original_response

shut elk
#

But if i defer, I can't put the view there of making it (the button) disabled

shut elk
fading marlin
#

sure

shut elk
#

That works after defering?

#

Oh yeah cuz its not response

#

ok, I'll try it ty

pulsar kettle
#

Just finished fixing the handling error portion, however even though a member without kick_members cannot kick a member, the bot still sends the kick DM to the person without kicking them. I assume it has something to do with the way I put the DM before the kick since my bot cannot DM someone it does not share a server with, so how can I fix this?

@bot.tree.command(name='kick', description='Kicks a member from the server')
@has_permissions(kick_members=True)
async def kick(interaction: discord.Interaction, member: discord.Member, reason: str=None):
    guild = interaction.guild
    await member.send(f"You have been kicked from: ***{guild.name}*** | {reason}")
    await member.kick(reason=reason)
    embed = discord.Embed(title=(f'***{member} has been kicked*** | {reason}'), color=0xf6ff00)
    await interaction.response.send_message(embed=embed)

@kick.error
async def kick_error(interaction: discord.Interaction, error):
    error = getattr(error, "original", error)
    await interaction.response.send_message("You do not have permission to use this command!")```
sick birch
#

Either you send the message after the kick and risk having the message not be delivered or you put up with with the message being sent regardless

pulsar kettle
#

Wait I just realised using the kick command kicks the member but the bot responds with "You do not have permission to use this command!" even tho the kick was successful

#

And it also didn't DM the member

young dagger
#

How can I show the timestamp using the format?

        timestamp = infraction["timestamp"]
        field_name = f"{infraction['type']} • <t:{timestamp}:f>"```
#

Doesn't look too good as you can tell

shut elk
fading marlin
#

You're welcome!

pulsar kettle
fading marlin
young dagger
naive briar
unkempt canyonBOT
#

datetime.timestamp()```
Return POSIX timestamp corresponding to the [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instance. The return value is a [`float`](https://docs.python.org/3/library/functions.html#float "float") similar to that returned by [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time").

Naive [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instances are assumed to represent local time and this method relies on the platform C `mktime()` function to perform the conversion. Since [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") supports wider range of values than `mktime()` on many platforms, this method may raise [`OverflowError`](https://docs.python.org/3/library/exceptions.html#OverflowError "OverflowError") for times far in the past or far in the future.

For aware [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instances, the return value is computed as:

```py
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
```   New in version 3.3.

Changed in version 3.6: The [`timestamp()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp "datetime.datetime.timestamp") method uses the [`fold`](https://docs.python.org/3/library/datetime.html#datetime.datetime.fold "datetime.datetime.fold") attribute to disambiguate the times during a repeated interval.
naive briar
#

!d discord.utils.format_dt

unkempt canyonBOT
#

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

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

Or that

pulsar kettle
#

However it still kicks the member

naive briar
#

There's already a built-in kick command

young dagger
#

Oh yeah I remember this one.

        timestamp = infraction["timestamp"]
        fmt_time = discord.utils.format_dt(timestamp, "f")
        field_name = f"{infraction['type']}{fmt_time}"```
pulsar kettle
ionic garden
fading marlin
#

!d discord.ext.commands.CogMeta you can pass a dictionary with its key as hidden and value as True to command_attrs

unkempt canyonBOT
#

class discord.ext.commands.CogMeta(*args, **kwargs)```
A metaclass for defining a cog.

Note that you should probably not use this directly. It is exposed purely for documentation purposes along with making custom metaclasses to intermix with other metaclasses such as the [`abc.ABCMeta`](https://docs.python.org/3/library/abc.html#abc.ABCMeta "(in Python v3.11)") metaclass.

For example, to create an abstract cog mixin class, the following would be done...
fading marlin
#

Then you can filter commands in your help command and autocomplete

golden portal
ionic garden
#

where do i use this CogMeta?

golden portal
#

!d discord.ext.commands.CogMeta.command_attrs

unkempt canyonBOT
#

A list of attributes to apply to every command inside this cog. The dictionary is passed into the Command options at __init__. If you specify attributes inside the command attribute in the class, it will override the one specified inside this attribute. For example:

class MyCog(commands.Cog, command_attrs=dict(hidden=True)):
    @commands.command()
    async def foo(self, ctx):
        pass # hidden -> True

@commands.command(hidden=False)
    async def bar(self, ctx):
        pass # hidden -> False
golden portal
#

this example in particular, you dont really "use" the cogmeta, the cogmeta is already with the commands.Cog

pulsar bridge
#

Trying to send a list of items to a typing.Literal converter using a function that calls the needed items from an external text file, but I've hit a dead end.

async def funtTags(): # Function Defining
    async with aif.open((directory + '\\' + 'list.txt'), 'rt') as file: # Opens the list file
        tags = await file.read() # Reading file
        tags_dict = ast.literal_eval(tags) # As the file is a dictionary, I have to convert it
        x = tags_dict['tags'].keys() # Get the keys
        return x # Returns x

And the actual command

@client.tree.command(name='add_note', description="Save a quick note for instant access to it later!")
async def create(interaction: discord.Interaction, title: str, tags: typing.Literal[funtTags()], source: str = None): # <- Calling the function here
    print('Success')

Any ideas?

naive briar
#

Why

desert heart
#

You will have to create your own converter class. typing.Literal does not support dynamically specifying multiple values.

pulsar bridge
desert heart
#

Or just perform the validation within the function

pulsar bridge
#

How'd I do that? for the latter one?
I still have yet to learn how to do either <.<;;

naive briar
#

!e

import inspect
import typing


attrs = {0: None, 1: None}.keys()
def cmd1(para: typing.Literal[attrs]):
    pass

print(inspect.signature(cmd1))

attrs = (0, 1)
def cmd2(para: typing.Literal[attrs]):
    pass

print(inspect.signature(cmd2))
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | (para: Literal[dict_keys([0, 1])])
002 | (para: Literal[0, 1])
naive briar
#

Either way, you shouldn't be doing this 🐈

desert heart
#

Oh, so the trick is just to use a tuple instead of a list

pulsar bridge
desert heart
#

If the file you're reading does not change, then you should cache its content to avoid reading it every time the command is invoked

pulsar kettle
#

Attempting to code a purge command, however upon running the command I always get the error discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction which I suspect is because the purge deletes the command message so it cannot reply. How can I work around this?

@bot.tree.command(name='purge', description='Deletes a specified number of messages from a channel')
@discord.app_commands.checks.has_permissions(administrator=True)
async def purge(interaction: discord.Interaction, limit: int):
    embed = discord.Embed(title=(f'Purged {limit} messages'), color=0xf6ff00)
    await interaction.channel.purge(limit=limit)
    await interaction.response.send_message(embed=embed)

@purge.error
async def purge_error(interaction: discord.Interaction, error):
    error = getattr(error, "original", error)
    await interaction.response.send_message("You do not have permission to purge messages!")```
naive briar
#

It took too long to respond

#

Defer the interaction before calling purge method

pulsar kettle
# naive briar Defer the interaction before calling purge method

Like this?

async def purge(interaction: discord.Interaction, limit: int):
    embed = discord.Embed(title=(f'Purged {limit} messages'), color=0xf6ff00)
    await interaction.response.defer()
    await interaction.channel.purge(limit=limit)
    await interaction.response.send_message(embed=embed)```
#

Because if so now I get the error discord.errors.InteractionResponded: This interaction has already been responded to before

unkempt canyonBOT
pulsar kettle
#

Triedinteraction.followup.send, but bot doesn't send Purged {limit} messages and I still get the error discord.errors.InteractionResponded: This interaction has already been responded to before

async def purge(interaction: discord.Interaction, limit: int):
    embed = discord.Embed(title=(f'Purged {limit} messages'), color=0xf6ff00)
    await interaction.response.defer()
    await interaction.channel.purge(limit=limit)
    await interaction.followup.send(embed=embed)```
slate swan
young dagger
#

How I can make a line break for each embed.add_field(name=field_name, value=field_value, inline=False)?

slate swan
#

like a divider between each embed?

young dagger
sick birch
young dagger
#

Is there any way to add new lines with (\n) in field_name?

pulsar kettle
slate swan
young dagger
pulsar kettle
sick birch
#

Yeh

young dagger
#

I want each entry to have a space in between

slate swan
young dagger
slate swan
# pulsar kettle Attempting to code a purge command, however upon running the command I always ge...
@discord.app_commands.checks.has_permissions(administrator=True)
async def purge(interaction: discord.Interaction, limit: int):
    command_message = interaction.message
    await interaction.channel.purge(limit=limit)
    embed = discord.Embed(title=(f'Purged {limit} messages'), color=0xf6ff00)
    await command_message.channel.send(embed=embed)

@purge.error
async def purge_error(interaction: discord.Interaction, error):
    error = getattr(error, "original", error)
    await interaction.response.send_message("You do not have permission to purge messages!")

try this

slate swan
#

im trying to help someone out?

#

it was resolved in dms, if i did something wrong i apologise

upbeat otter
slate swan
#

im new to this server and will get inline with the rules

#

i apologise again, wont happen again

upbeat otter
slate swan
#

thanks for explaining that rule to me, ill take it into consideration next time

upbeat otter
pulsar kettle
#

Trying to code my own AFK feature for my bot, but I am completely unsure on how I can get the bot to check if any mentioned user has "[AFK]" in their name, and if they do, the bot sends a message. Can anybody please help me out? (I will definitely need explanations because I have little idea on what I'm doing lol)

@bot.tree.command(name='afk', description='Sets an AFK status to display when you are mentioned by another member')
async def afk(interaction: discord.Interaction, reason: str=None):
    if interaction.user.nick == None:
        await interaction.user.edit(nick=(f'[AFK] {interaction.user.name}'))
        embed = discord.Embed(title=(f"Changed your status to AFK | {reason}"), color=0xf6ff00)
        await interaction.response.send_message(embed=embed)
    else:
        await interaction.user.edit(nick=(f'[AFK] {interaction.user.nick}'))
        embed = discord.Embed(title=(f"Changed your status to AFK | {reason}"), color=0xf6ff00)
        await interaction.response.send_message(embed=embed)```
#

So far I've only got the first part of the code working which adds [AFK] to somebody's username

sick birch
#

You'd check message.mentions inside an on_message

#

Loop through each Member in message.mentions, check if "[AFK]" in mentioned_member.nick

slate swan
#

tbh a database would work much better here but yeah you can do this as a shortcut

#

cons would be that bot won't be able to set afk for users with higher roles

#

or if a user changes their nickname themselves the afk will be removed

pulsar kettle
#

Ideally

ionic garden
#

for a decorator check like this:

def is_registered():
    async def predicate(ctx: commands.Context) -> bool:
        if not dm.is_registered(ctx.author.id):
            raise UserNotRegistered
        return True

    return commands.check(predicate)
```i have to call it like so:
```py
@is_registered()
```this is a question that pertains more to python in general, but is there a way to code decorators so that parens aren't needed?
slate swan
#

you can use the @decorator syntax but im pretty sure this syntax is not supported by Python since version 2.4

#

dont quote me on that though

pulsar kettle
slate swan
unkempt canyonBOT
#

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

...
ionic garden
#

ah, you call it in the decorator itself

#

thanks

slate swan
#

given that a check requires a context, this won't be valid for discord.py checks
but yeah you can use decorators without calling them over function

slate swan
pulsar kettle
slate swan
#

message.channel.send

#

or message.reply if you wanna reply

pulsar kettle
subtle jolt
#

if i set a button to disabled with button.disabled = True,
how do i update it if is in a slash command response?
this wont work await interaction.edit_original_response(view=self)

slate swan
#

disable it from view's children

#

!d discord.ui.View.children

unkempt canyonBOT
slate swan
#

and message.author.edit to change nickname again

subtle jolt
slate swan
#

this will disable all buttons yeah

subtle jolt
#

yeah that works but how do i update the button for this to take effect

pulsar kettle
snow trench
#

Guys how can I keep my discord.py bot on 24/7? For free

slate swan
maiden fable
#

Replit You gotta pay for hosting but there's free packages by various hosting services. Checkout #965291480992321536 @snow trench

slate swan
#

i love the new syntax highlighting

#

!d discord.Member.edit is it nick or nickname

unkempt canyonBOT
#

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

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below...
slate swan
#

nick yeah

maiden fable
#

The newer colors are brighter as well

pulsar kettle
# slate swan assuming member to be the message author ```py await member.edit(nick=member.dis...

Returns error: UnboundLocalError: cannot access local variable 'member' where it is not associated with a value

@bot.listen()
async def on_message(message):
    if message.author.bot:
        return
    if message.mentions:
        for member in message.mentions:
            if "[AFK]" in member.display_name:
                await message.reply('This user is currently AFK')
            else:
                return
    if "[AFK]" in message.author.display_name:
            await message.reply('Welcome back, I have removed your AFK status')
            await member.edit(nick=member.display_name.replace("[AFK]",""))
    else:
        return```
#

On this line: await member.edit(nick=member.display_name.replace("[AFK]",""))

maiden fable
#

Indent issues prolly

slate swan
#

assuming member to be the message author
define the variable first

pulsar kettle
#

Jsut noticed indents yeah

slate swan
#

you should also continue, not return in the second if statement

upbeat otter
pulsar kettle
# slate swan > assuming member to be the message author define the variable first

Everything's working as intended now, final question (sorry): If I want to put the AFK reason in User is currently AFK | {reason}, how can I pull the variable from:

@bot.tree.command(name='afk', description='Sets an AFK status to display when you are mentioned by another member')
async def afk(interaction: discord.Interaction, reason: str=None):
    if interaction.user.nick == None:
        await interaction.user.edit(nick=(f'[AFK] {interaction.user.name}'))
        embed = discord.Embed(title=(f"Changed your status to AFK | {reason}"), color=0xf6ff00)
        await interaction.response.send_message(embed=embed)
    else:
        await interaction.user.edit(nick=(f'[AFK] {interaction.user.nick}'))
        embed = discord.Embed(title=(f"Changed your status to AFK | {reason}"), color=0xf6ff00)
        await interaction.response.send_message(embed=embed)```
slate swan
#

that's where the "you should be using a database" point comes from

#

not possible without a database or a cache

#

the cache will be lost everytime the bot restarts

#

so database is the only dependable choice

pulsar kettle
#

Is it difficult to implement?

maiden fable
#

Not if bot.on_error helps u

slate swan
#

depends on what database you use, but yeah it's easy

pulsar kettle
#

I see, because this discord bot I'm working on is sort of my first "real" entry into coding since the stuff they taught in my schools was either irrelevent or extremely simple

#

Kinda just learning as I go along aha

slate swan
#

well databases are a nice to know about, it will be useful in any case related to storage

#

for the basics 3-4 lines of sql query is all you need to learn

pulsar kettle
#

Are there any notable guides I could follow that would work with my bot + others if I decide to branch out?

slate swan
#

well first choose a database, there's mainly sql and nosql database
and both categories have flavours of own

#

for starters i'll suggest sqlite3 as it's inbuilt in python too, doesnt need a server setup ( it just uses a file in your project ) and doesnt need much effort to learn

#

20-30 minutes is all you'll need to put to learn basics

pulsar kettle
#

Aight I'll look into it, tysm for you help <3

slate swan
sudden beacon
#

hey

#

can anyone help me with discord oauth2 join guild and user authentication ?

flint hare
#

a github repo for bots?

rare echo
flint hare
subtle jolt
#

how do you make slash command input suggestions like so:

regal nebula
subtle jolt
#

thanks

sudden beacon
sudden beacon
light violet
#

how do i get message.webhook?

#

pls help me

swift pine
#

mmmm ┬─┬ノ( º _ ºノ)

light violet
#

what pls help me

upbeat otter
light violet
vale wing
unkempt canyonBOT
#

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

x == y Checks if two messages are equal.

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

hash(x) Returns the message’s hash.
light violet
#

.

vale wing
#

Look at last attribute

#

That's very pointing

light violet
#

oo webhook_id

#

should i fetch the webhook by channel.fetch_webhook?

#

oo got it client.fetch_webhook

unkempt canyonBOT
#

@light violet, looks like you posted a Discord webhook URL. Therefore, your message has been removed, and your webhook has been deleted. You can re-create it if you wish to. If you believe this was a mistake, please let us know.

#

@light violet, looks like you posted a Discord webhook URL. Therefore, your message has been removed, and your webhook has been deleted. You can re-create it if you wish to. If you believe this was a mistake, please let us know.

light violet
#

@vale wingwhy am i getting the url after fething as discord.com/api/webhooks/1061921432981995531/None

#

none as token?

#

cant get the url by myself also how the heck

#

its blocked

abstract owl
#

@sick birch im making a premium user command or admin command, so that the only people i add in the bot can use the command, now when i type -config_addadmin <id> It adds the id to the config file but doesnt work until i reload the json. Any way to solve that?

upbeat otter
abstract owl
#

and loading the owner_id too

light violet
#

pls help me also

upbeat otter
abstract owl
#

yea

upbeat otter
# abstract owl

idk why that would be happening really
why don't you load the file using json.load(f) though, I think that is easier than opening the json file and extracting content as a string and then turning it into a json object

abstract owl
#

oh

#

I'll try

#

i fixed it, it was taking a global variable as the config file. I changed its variable to smth else and works now tysm ash

upbeat otter
#

nice

light violet
#

why is it

terse orchid
#

hiya, how would I run an async function in the background? I need to run a while loop to check the time but want to be able to use other functions concurrently

shrewd apex
#

check perms

light violet
shrewd apex
#

also lol dont share webhook anyone can use it to spam the channel

light violet
#

that copy url button

light violet
#

@shrewd apexsee this

#

how is it

shut star
#

?

#

i have a bit of experience in dpy

#

whats the problem

#

nvm u sent the code

#

from my memory that should work?

slate swan
#

if your code is running you're on an ancient version of discord.py

#

update discord.py, the code for sending message is wrong

shut star
slate swan
#

im not familiar with selfbot libraries so idk

#

yeah no client.send_message is not a thing

shut star
slate swan
#

not anylonger

shut star
#

nope, you still can

#

just downgrade dpy

#

update ur dpy

#

and shouldnt it be ctx.send?

slate swan
#

discord has discontinued the api version that self bots need, even if you selfbot you won't be able to read messages without fetching

#

someone tried that lol

light violet
#

why dont you try ctx.send(embed=embed)

shut star
#

well it works for me

light violet
#

no need to define mess ch

shut star
#

just tested it

#

!ping still works with older dpy

unkempt canyonBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

light violet
#

reinstall dpy

shut star
#

why was it an older version anyway?

light violet
#

try that line and gimme the error

#

did u reinsall?

#

see the console log the lines with error and show me

potent spear
#

so your randomjoke command has some flaws ig

#

you read that right

#

could you put this in

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

light violet
#

the whole code

#

?

potent spear
#

why is EVERYTHING in a run_discord_bot function? 🤢

#

that's an issue, you know

light violet
#

yea complex

potent spear
#

red flag

light violet
#

hmm

potent spear
#

YT is one of the shitties ways of learning this kind of library

light violet
#

hmm

#

do u know py basics?

potent spear
#

mostly because this library changes quickly and tutorials get outdated
most tutorials on yt are incorrect anyways

#

use official documentation and learn that way

potent spear
light violet
#

i think this should work

#

i made it for you

subtle jolt
#

can you edit a interaction.response and include a file?

#

TypeError: InteractionResponse.edit_message() got an unexpected keyword argument 'file'

potent spear
#

just edit

#

edit_message is the internal command function 😉

light violet
#

why did u del my msg

potent spear
#

I didn't...

light violet
#

who did it lmao

potent spear
#

the bot most likely

light violet
#

hmm

subtle jolt
tough fern
#

hello, how to make bot (AutoShardedBot) react to message (to be exact using custom emojis)

potent spear
potent spear
light violet
potent spear
potent spear
light violet
#

hm

tough fern
potent spear
tough fern
#

oh ok

subtle jolt
#

or can it be a directory

#

code:

await interaction.response.edit_message(content=f"{self.name}'s {mode} session:", attachments=[f'{os.getcwd()}/assets/{mode}_{self.session}.png'])```

error:
```python
AttributeError: 'str' object has no attribute 'to_dict'```
potent spear
#

spoiler: ||a string to a file in your directory will not work, you need to pass a file OBJECT||

crimson mauve
potent spear
subtle jolt
crimson mauve
subtle jolt
#

i made an app that added one number to the other

#

and then put it on github

crimson mauve
#

Can you humor me real quick? What's a String?

potent spear
potent spear
crimson mauve
potent spear
#

technically correct

gloomy jackal
potent spear
#

thank you, google

gloomy jackal
#

I Am GOOOOOOOOGLE

gloomy jackal
crimson mauve
potent spear
#

luca||'t my balls||?

gloomy jackal
gloomy jackal
crimson mauve
gloomy jackal
crimson mauve
gloomy jackal
gloomy jackal
crimson mauve
gloomy jackal
# crimson mauve Pass

NOooo, I will now eternally live under a rock thinking about how u rejected me as a friend, How could u do that to me!?

crimson mauve
gloomy jackal
crimson mauve
gloomy jackal
crimson mauve
gloomy jackal
gloomy jackal
gloomy jackal
shrewd fjord
#

Sup

crimson mauve
shrewd fjord
crimson mauve
shrewd fjord
#

Zippy, cool name 🙂

shrewd fjord
#

I am actually here to help ppl 🗿

#

But there is no one 🤧

crimson mauve
#

It's still early/late for most people.

subtle jolt
shrewd fjord
unkempt canyonBOT
#

clear_items()```
Removes all items from the view.

This function returns the class instance to allow for fluent-style chaining.
shrewd fjord
#

Wait a sec

#

U need to edit the message btw to do it

crimson mauve
subtle jolt
subtle jolt
#

perfect timing

#

I turned off my pc

crimson mauve
subtle jolt
#

I did

#

its 2am

crimson mauve
subtle jolt
#

its for the funny

crimson mauve
#

Funny is for people that know you, I don't know you.

subtle jolt
#

but I find it funny

crimson mauve
#

Cool, and it makes you look like a troll to me.

subtle jolt
#

define 'troll'

crimson mauve
subtle jolt
#

like the thing under the bridge or...

crimson mauve
#

Yup, I was right.......

subtle jolt
#

OK now I'm actually under the bridge

#

I wasnt before

crimson mauve
#

Did you get an error?

light violet
#

Show the error

#

.

crimson mauve
#

Message can't be empty.

light violet
#

@crimson mauve he send an embed

#

Check the code

crimson mauve
light violet
#

Check the code herehttps://paste.pythondiscord.com/nanukebaxu

crimson mauve
#

need the entire traceback

#

await ctx.send(mess_channel, embed=embed)

light violet
#

Sorry it was my mistake maybe

crimson mauve
#

!d discord.abc.Messageable.send

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

Sends a message to the destination with the content given.

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

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

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

Heres the updated one

#

Check it

young dagger
#

How I can make a line break for each embed.add_field(name=field_name, value=field_value, inline=False)? Each infraction is listed in field_name and field_value, same embed. I want to add a line break for each one of them. https://paste.pythondiscord.com/zokuputubu

light violet
crimson mauve
#

Are you sure that's the entire traceback?

tawny junco
#

Where does one host a discord bot 24/7 for the sake of development (free) besides replit?

light violet
#

. Gitlab

#

@slate swan whats the ping? There

#

@slate swan what is your bot ping in discloud

tawny junco
light violet
#

U can use glitch if u arent coding in dpy

upbeat otter
tawny junco
#

I code on my phone

upbeat otter
#

pro 🛐

crimson mauve
light violet
#

I also code on mobile and got my bot verified

tawny junco
light violet
#

Error

upbeat otter
#

ok and

#

your code?

tawny junco
#

Do I need to sign up with credentials?

crimson mauve
#

Ya, kinda useless without the full traceback telling us where it went wrong.

upbeat otter
#

^

#

show the code where you send the message

tawny junco
#

Right. Perfect since my credentials expired

#

Replit keeps installing dependencies everytime I run my code. So annoying.

upbeat otter
#

It's discord.Colour/discord.Color

#

discord.color is a file

pulsar kettle
#

Attempting a timeout command for my bot, and I know I've definitely got some things wrong. Can anyone help out please?

@bot.tree.command(name='timeout', description='Times out a member')
@discord.app_commands.checks.has_permissions(moderate_members=True)
async def timeout(interaction: discord.Interaction, member: discord.Member, time: int=None, reason: str=None):
    if reason == None:
        reason = "No reason provided"
    guild = interaction.guild
    await member.send(f"You have been timed out in: ***{guild.name} for {time}*** | {reason}")
    await member.timeout(time, reason=reason)
    embed = discord.Embed(title=(f'***{member} has been timed out for {time}*** | {reason}'), color=0xf6ff00)
    await interaction.response.send_message(embed=embed)```
Error: ``discord.app_commands.errors.CommandInvokeError: Command 'timeout' raised an exception: TypeError: expected None, datetime.datetime, or datetime.timedelta not int``
crimson mauve
#

Whos code is this? Who did you copy it from?

#

await send_message(message, user_message, is_private=True)

upbeat otter
#

average

pulsar kettle
#

I want to be able to input smth like 5s for 5 second or 24h for 24 hours but idk how to do convertors or apply them in discord.py itmeouts

crimson mauve
#

ofc?

upbeat otter
#

they copied it from youtube

crimson mauve
#

ofc stand for of fucking course right?

#

OFC was the channel then?

#

Either way, your code is a mix of stuff from now and from years ago.

unkempt canyonBOT
crimson mauve
#

???

upbeat otter
#

?

#

slangs?

crimson mauve
#

What?

#

You ok?

upbeat otter
crimson mauve
#

ok?

pulsar kettle
#

Isn't ofc just shortened version of "of course"

crimson mauve
#

What's that got to do with anything?

upbeat otter
pulsar kettle
crimson mauve
#

But back to the real topic, your code ain't going to work because it's a mix of versions.

upbeat otter
crimson mauve
#

await send_message(message, user_message, is_private=True) has not been used in like, 3 years?

upbeat otter
amber ether
#

Hello, Im currently new to python and asking how are indentations work? i have been having problems

crimson mauve
#

My bad, I'll be sure to not say anything from now on then.

upbeat otter
#

good luck Peepo_Blush

unkempt canyonBOT
#

Indentation

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

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

Example

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

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

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

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

upbeat otter
#

what just happened
I do think I provided the solution in the very beginning
but ok
idc

maiden fable
#

He is just thanking you dude

upbeat otter
#

pepe_exit assuming genders in 2023

maiden fable
#

Knew u were gonna say that

crimson mauve
amber ether
unkempt canyonBOT
#

Indentation

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

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

Example

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

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

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

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

upbeat otter
pulsar kettle
#

Another attempt at a timeout slash command, now I get the error discord.app_commands.errors.CommandInvokeError: Command 'timeout' raised an exception: TypeError: unsupported type for timedelta minutes component: NoneType. Any ideas on how to fix/optimize this?

@bot.tree.command(name='timeout', description='Times out a member')
@discord.app_commands.checks.has_permissions(moderate_members=True)
async def timeout(interaction: discord.Interaction, member: discord.Member, reason: str=None, days: int=None, hours: int=None, minutes: int=None, seconds: int=None):
    if member.id == interaction.user.id:
        await interaction.response.send_message("You can't timeout yourself!")
        return
    if member.guild_permissions.moderate_members:
        await interaction.response.send_message("You can't do this, this person is a moderator!")
        return
    duration = timedelta(days = days, hours = hours, minutes = minutes, seconds = seconds)
    if duration >= timedelta(days = 28): #added to check if time exceeds 28 days
        await interaction.response.send_message("I can't mute someone for more than 28 days!", ephemeral = True) #responds, but only the author can see the response
        return
    if reason == None:
        await member.timeout_for(duration)
        await interaction.response.send_message(f"<@{member.id}> has been timed out for {days} days, {hours} hours, {minutes} minutes, and {seconds} seconds by <@{interaction.user.id}>.")
    else:
        await member.timeout_for(duration, reason = reason)
        await interaction.response.send_message(f"<@{member.id}> has been timed out for {days} days, {hours} hours, {minutes} minutes, and {seconds} seconds by <@{interaction.user.id}> for '{reason}'.")```
bright wedge
#

for first look

duration = timedelta(days = days, hours = hours, minutes = minutes, seconds = seconds)
if duration >= timedelta(days = 28): #added to check if time exceeds 28 days
  await interaction.response.send_message("I can't mute someone for more than 28 days!", ephemeral = True) #responds, but only the author can see the response

else:
  reason = reason if reason != None else None
  await member.timeout_for(duration, reason = reason)
  await interaction.response.send_message(f"<@{member.id}> has been   timed out for {days} days, {hours} hours, {minutes} minutes, and     {seconds} seconds by <@{interaction.user.id}> for '{reason}'.")
crimson mauve
#

I see

bright wedge
crimson mauve
pulsar kettle
#

So how would I go about fixing the code? (I'm new to discord.py so smoothbrain)

crimson mauve
amber ether
#

Fixed it all but why am i getting this? This code was just working earlier?

pulsar kettle
crimson mauve
crimson mauve
crimson mauve
amber ether
crimson mauve
amber ether
#

im so used to on js lol

crimson mauve
amber ether
#

ye

#

Ohh my gosh aahh, im so confused where to put this.

crimson mauve
amber ether
#

cuz without that not_good wouldnt work.

crimson mauve
#

I mean, what is the list for, what are you doing with it?

crimson mauve
#

Because you still need to define what spots is.

#

your list is calling for spots, not defining it.

amber ether
crimson mauve
#

Your traceback is flat out saying that spots is not defined.

#

It's not me saying that, it's your computer.

amber ether
#

Now it works i put mines int etc at top ey

crimson mauve
#

Also, you don't need to define data types in python like you do in other languages.

Int = 89734598734
String = "34905835"
light violet
#

L

crimson mauve
white perch
#

Hi!
What's the best way to carry out scheduled events in a discord bot?
For example, every day at 12 am the bot should be posting a message in a channel...
I know a while loop can be run and compared with the current datetime and the scheduled datetime, but is this an efficient method to do it? Any suggestions?

crimson mauve
white perch
cloud dawn
#

!d discord.ext.tasks.Loop.time

unkempt canyonBOT
#

property time```
Read-only list for the exact times this loop runs at. `None` if relative times were passed instead.

New in version 2.0.
white perch
#

Oh

light violet
crimson mauve
cloud dawn
#

!d datetime.timedelta @white perch

unkempt canyonBOT
#

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

Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
white perch
#

Oh i just realized that tasks have a time parameter

crimson mauve
cloud dawn
white perch
#

How to handle this in case our bot is customizable?
Like any server can set any time for sending the message

white perch
cloud dawn
unkempt canyonBOT
cloud dawn
white perch
#

Oh um

#

I'll try coding that, will ask if i don't manage to logically get the code right

light violet
light violet
#

By da way which L are you talking about

crimson mauve
light violet
light violet
slate swan
#

How can i have the same @commands.group() in 2 cogs. Can someone help? @crimson mauve im back xD

light violet
cloud dawn
crimson mauve
upbeat otter
#

based

slate swan
#

:D

white perch
#

Idk how Dyno handles this

upbeat otter
white perch
#

Dyno & carl bot, etc they somehow do it customizably for each server

cloud dawn
cloud dawn
white perch
crimson mauve
slate swan
white perch
#

How to evaluate the event logically at the time without using a while loop is difficult according to me

slate swan
white perch
#

A while loop would take too much cpu resource

cloud dawn
white perch
cloud dawn
white perch
white perch
#

If it's only for one server then it's easy to get it coded

#

Anyway i will try to code it now- let's see if it goes well

cloud dawn
sudden nacelle
#

Finished my server lockdown command which correctly locks every channel and sends the embed, however idk why it still says "Bot is thinking..." even though the command is complete. Any thoughts? (no error messages in VSC)

@bot.tree.command(name='lockdown', description='Puts server into lockdown')
@discord.app_commands.checks.has_permissions(manage_channels=True)
async def lockdown(interaction: discord.Interaction):
    embed = discord.Embed(title=(f'The server is now on lockdown'), color=0xf6ff00)
    await interaction.response.defer()
    for channel in interaction.guild.channels:
        await channel.set_permissions(interaction.guild.default_role, send_messages=False)
    await interaction.channel.send(embed=embed)```
cloud dawn
#

!d discord.Interaction.followup

unkempt canyonBOT
sudden nacelle
shrewd apex
#

just edit the original response lol

cold sonnet
#

do y'all go to the gym

crimson mauve
cold sonnet
#

that's a no

#

start that

crimson mauve
#

lol

cold sonnet
#

it's funny to be jacked as a programmer

crimson mauve
#

Cool story bro.

cold sonnet
#

do you know where I am rn

cloud dawn
#

!ot

unkempt canyonBOT
cold sonnet
#

!topic

unkempt canyonBOT
cold sonnet
#

what

crimson mauve
cold sonnet
#

oh .topic

cold sonnet
#

.topic

lament depotBOT
#
**What feature would you be the most interested in making?**

Suggest more topics here!

crimson mauve
cold sonnet
cold sonnet
crimson mauve
cold sonnet
#

nobody's typing in the channel

#

so

#

you're welcome

crimson mauve
#

if this is all you have to say, I would prefer the silence.

cold sonnet
#

did you know discord.py still doesn't have voice receiving

crimson mauve
#

So?

#

I don't see much of a use for it anyway.

cold sonnet
#

but I do

crimson mauve
#

Such as?

cold sonnet
#

voice commands

#

when you're in-game

crimson mauve
#

At that point why do you need Discord?

cold sonnet
#

no relation whatsoever

sick birch
#

I wonder if voice reception events get triggered by on socket raw receive

crimson mauve
#

I mean, Speech to text is fun and all but unless you have to time/recourses to toss at it you are just going to be upset with the results.

#

Even Google and Amazon still suck at it.

cold sonnet
#

do discord.py perfect voice receiving and get a job at google

crimson mauve
#

No, I would be leasing my tech, not giving it away.

cold sonnet
#

also smart

crimson mauve
#

But ya, you need any help?

cold sonnet
#

I always like a challenge

#

no

#

🤨

cold sonnet
young dagger
#

How can I get this code work?

@modlogs.error
async def modlogs_error(ctx, error):
    if isinstance(error, commands.MemberNotFound):
        await ctx.send(f"I could not find the user {error.member_str}")```
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'MemberNotFound' object has no attribute 'member_str

young dagger
#

Oh that makes sense, thanks

white perch
#

can embeds be stored in database directly as discord.Embed object and later re loaded directly?

crimson mauve
white perch
#

Customizable Embeds feature

crimson mauve
#

But why would you store them and not make them as you need them?

white perch
#
  1. embed elements input by user
  2. embed stored in database with some user inputted name
  3. user does $load_embed {name}
  4. bot sends their embed
#

That's what im upto

crimson mauve
#

Ok, I get you now.

#

Depends on the DB, but generally they don't work well with custom objects like that. You would have to break it up into parts.

white perch
#

Ah

#

Alr

shrewd apex
white perch
#

Hmm

#

Is there a built-in way to convert an embed to a dict or any readymade remedy?

white perch
crimson mauve
white perch
#

Rightly said

cold sonnet
#

!d discord.Embed or you look at the api reference to get your answer

unkempt canyonBOT
#

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

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

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

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
white perch
#

aight

crimson mauve
white perch
#

found it man

crimson mauve
#

Awesome

white perch
#

embed.to_dict
and embed.from_dict

#

thank you

crimson mauve
#

Any time Mike.

cloud dawn
#

Then eval it lol

shrewd apex
fading marlin
#

sqlite ducky_sphere

cloud dawn
cold sonnet
#

u can afford to host a bot but not sql?

shrewd apex
#

lol

cold sonnet
#

heh

cloud dawn
#

Just host a vps with a postgresql

shrewd apex
#

internet

#

latency be like

cloud dawn
#

Or a docker container

cold sonnet
#

raspberry pi

#

💪

cloud dawn
#

Pregnancy test cpu

#

🙄

#

I mean it ran doom

crimson mauve
#

I'm looking forward to the first person that gets their hands on alien tech also gets it to run doom as a proof of concept.

abstract owl
#

am i doing smth wrong? the appeared one works fine the congratulations doesn't

cloud dawn
#

!global

unkempt canyonBOT
#

When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.

Instead of writing

def update_score():
    global score, roll
    score = score + roll
update_score()

do this instead

def update_score(score, roll):
    return score + roll
score = update_score(score, roll)

For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.

cloud dawn
#

Btw python v4.12 mans from the future

crimson mauve
#

When that first if statement goes though, the elif is ignored and not even checked.

abstract owl
crimson mauve
crimson mauve
abstract owl
#

marvelously fixed it

unkempt canyonBOT
onyx rapids
onyx rapids
#

wait, where do I put that then?

crimson mauve
crimson mauve
onyx rapids
#

didnt work

crimson mauve
#

Ah crap, what did I say this time?

onyx rapids
onyx rapids
steep wedge
crimson mauve
#

I'm only one person.

#

So what? lol, dude I'm spending my time here helping people for nothing but my time.

steep wedge
#

you aren't doing an amazing job at it to be honest

steep wedge
crimson mauve
abstract owl
#

tfym atleast he comes here everyday helping at as best as he can 😭

steep wedge
crimson mauve
steep wedge
#

flippin ChatGPT is better help than that

abstract owl
cloud dawn
steep wedge
crimson mauve
onyx rapids
cloud dawn
#

That's ok too, It's a public server, try to keep it cool here.

crimson mauve
#

You want to take over for a bit panda? I think I'm going to work on my own stuff for a bit now.

cloud dawn
#

I just keep this channel on my second screen and coding a long the side :3
Keeps my mind busy and doing something else on ever now and then to avoid doing the same for 10 hours straight.

crimson mauve
onyx rapids
#

So which one do I have to remove?

steep wedge
#

is there a point using a vps for a private bot in a 20 member server

abstract owl
steep wedge
abstract owl
#

then no use host on repl or local machine

cloud dawn