#discord-bots

1 messages · Page 118 of 1

fading marlin
#

that looks about right, what exactly are you doubting?

slate swan
#

cus bruv

fading marlin
#

you have to start the task

slate swan
#

ctx

fading marlin
#

idk, __init__ if you want it to start as soon as the cog is initialized, a command if you want to toggle it

#

you don't need to, just throw it inside your init

#

sure

slate swan
#

@fading marlin

#

like do i not have a module or somethin installed

#

Fixed it nvm

slate swan
sick birch
#

Looks like all your commands are global

#

You might want to try using .copy_global_to

slate swan
#

where do I put .copy_global_to

sick birch
slate swan
# sick birch above the sync
.copy_global_to
async def sync(ctx) -> None:
    fmt = await ctx.bot.tree.sync(guild=ctx.guild)
    await ctx.send(
        f"Synced {len(fmt)} commands to current guild"
    )
    return

?

#

@sick birch

#

bro please help me

sick birch
unkempt canyonBOT
#

copy_global_to(*, guild)```
Copies all global commands to the specified guild.

This method is mainly available for development purposes, as it allows you to copy your global commands over to a testing guild easily.

Note that this method will *override* pre-existing guild commands that would conflict.
sick birch
#

i meant this not just adding that text to the code

#

above your await ctx.bot.tree.sync()

sick birch
#

it needs to be called on your tree instance

slate swan
# sick birch Read the documentation on how to use the function
async def sync(ctx) -> None:
    copy_global_to(*, guild=None, type=None)
    fmt = await ctx.bot.tree.sync(guild=ctx.guild)
    await ctx.send(
        f"Synced {len(fmt)} commands to current guild"
    )
    return``` 

**Its still an error can you please just help me so I can start slash commands
sick birch
#

It tells you exactly how to use it

slate swan
sick birch
#

Which part? I'd be happy to clarify

slate swan
#

I don't really know where to look to get my answer theres so many things I'm just trying to get my slash commands to appear

sick birch
#

if you'll notice, copy_global_to is under discord.app_commands.CommandTree

#

This means that copy_global_to has to be called on a dsicord.app_commands.CommandTree instance

#

Luckily - you've already got that!

#

ctx.bot.tree happens to be an instance of discord.app_commands.CommandTree

sick birch
sick birch
#

It also tells you the aguments the class takes

#

The first one, client is your client/bot instance (ctx.bot in your case). The 2nd argument is an optional, so you can ignore it if you'd like

#

Put together, it'll look like this:

await ctx.bot.copy_global_to(guild=ctx.guild)
#

That's my crash course on How To Read Documentation ™️

slate swan
#

I'm still confused on where to find the answer to my problem tho

sick birch
#

It's an invaluable skill, and learning how to do it efficiently will supercharge you as a developer, and allow you to focus on new features than fighting with the language/library/framework you're using

sick birch
#

Though I would highly recommend against copy pasting it and moving on

slate swan
sick birch
#

I'd recommend you take your time, analyze each part, and make sure you're 100% sure what's going on before you proceed, since this is fundamental. If you've got questions I'd be more than happy to answer them

#

No, you still need to be syncing

#

You just need to copy all of your global commands to a guild, then sync those copied commands with Discord

#

Reason being global commands can take up to 1 hour to propagate

slate swan
sick birch
#

Sure. Sounds good, though it still seems you're worried more about the final result than the intermediates, which are far more important 😄 I can't force you to of course, but just make sure you understand before moving on

slate swan
#

I just want to test out my slash command

sick birch
#

I can totally understand that - but if you don't get comfortable with problem solving and documentation skills, it'll only get harder. Not meant to discourage you, of course, just friendly advice you can keep in mind

slate swan
#

I got an error

sick birch
#

Let's see it

slate swan
#
  File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 986, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 199, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'client'```

Code: 
```@client.command()
async def sync(ctx) -> None:
    await ctx.bot.copy_global_to(guild=ctx.guild)
    fmt = await ctx.bot.tree.sync(guild=ctx.guild)
    await ctx.send(
        f"Synced {len(fmt)} commands to current guild"
    )
    return```
sick birch
#

Is that the whole error? Looks like parts are cut off

slate swan
slate swan
# sick birch Is that the *whole* error? Looks like parts are cut off
  File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\dynam\Documents\predictor\main.py", line 210, in sync
    await ctx.bot.copy_global_to(guild=ctx.guild)
AttributeError: 'Bot' object has no attribute 'copy_global_to'

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

Traceback (most recent call last):
  File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 986, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 199, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'copy_global_to'```

is full error
sick birch
#

Much better

#

Ah shit that's on me, it's ctx.bot.tree not just ctx.bot

#

My apologies

slate swan
#

and all good

sick birch
#

Leave the sync as it is

#

The line above, the copy global to part, it should be ctx.bot.tree.copy_global_to

#

right now its' ctx.bot.copy_global_to

#

Notice the difference? it can be a bit hard to spot

slate swan
#

oh ok

#

I'll re try

slate swan
sick birch
#

Full traceback, please

slate swan
#

I just reset and it worked bruh 😭

sick birch
#

It happens. May not have saved all the way

slate swan
#

For every slash command I do

sick birch
#

Can I see the pastebin of the entire code?

slate swan
sick birch
#

I've lost the link as I rebooted my computer

slate swan
sick birch
#

For which command specifically did it not respond?

sick birch
#

Hmmm

#

It should at least work for the login one

#

Try doing print statements in each, see if they get called

slate swan
#

print?

#

oh nvm

sick birch
#

Yeah, for instance

@client.tree.command(...)
async def login(...):
  print("Login command was called!")
slate swan
#

yea

sick birch
#

Do that for all 3, run your slash commands from discord, see what happens

slate swan
#

I'm unfamiliar with slash commands

#

Is this right?

async def login(ctx):
  print("Login command was called!")```
sick birch
#

Don't change any existing code

hushed galleon
#

if none of the commands responded, wouldnt there have been more tracebacks in the console?

sick birch
#

Just add the print statement as the first line in your slash command functions

sick birch
slate swan
#

alright one second

slate swan
# sick birch It would be helpful to see them otherwise we're just taking a shot in the dark a...
  File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 851, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "C:\Users\dynam\Documents\predictor\main.py", line 51, in balance
    user_info = collection.find({"user": user})
AttributeError: 'list' object has no attribute 'find'

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

Traceback (most recent call last):
  File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 1240, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 876, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 869, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'balance' raised an exception: AttributeError: 'list' object has no attribute 'find'```
sick birch
#

Or get the index of it?

slate swan
sick birch
#

Yeah, but what is the purpose of that line?

user_info = collection.find({"user": user})
#

What's it supposed to be doing?

slate swan
#

find the user

sick birch
#

Ahh, did you remove the database connection code?

#

I think collection is supposed to be something from your database, yes?

sick birch
#

Is it MongoDB?

slate swan
sick birch
#

Could you include the code? Remove any sensitive information like database URLs and login passwords

slate swan
sick birch
#

Is that all your database connection?

slate swan
sick birch
#

Well it looks like you're assuming collection is a MongoDB object, when it's just a regular list

#

So you'll have to change all of that to accomodate for it

slate swan
#

i am doing this but it just exits the app evereytime..

  name = input("\033[31mClick any key to return to menu")
except KeyboardInterrupt:
  os.system('cls')
  print(x)

BTW print(x) is just something it re prints out

#

im trying to make it reprint x but it just closes the prompt

#

someone???

granite plume
#

how do you convert message input (with wait_for command) into a str?

sick birch
granite plume
#

nevermind

#

you need to use message.content

sick birch
#
msg = await bot.wait_for("message", ...)
print(type(msg.content)) # <class 'str'>
granite plume
#

it is by default?

#

i was getting it to be type 'Message'

granite plume
granite plume
#

How do I get the "guess" command to work

unkempt canyonBOT
#

Hey @granite plume!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

granite plume
zealous jay
austere vale
#

does anyone know a way to shuffle music playlists? wavelink docs dont seem to have a command for it

sick birch
austere vale
#

ahh okay

#

is it against tos to do music bots with spotify too?

torn sail
#

Spotify doesn’t give you the music I think

#

Only gives info about the music

austere vale
#

oh ok

last belfry
#

!e

unkempt canyonBOT
#
Missing required argument

code

last belfry
#

!e
print ("hi")

#

!e

import wikipedia
user = input("Search here")
result =wikipedia.summary(user, sentences= 2)
print(result)```
unkempt canyonBOT
#

@last belfry :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'wikipedia'
paper sluice
#

#bot-commands

quick dust
#

yo anyone down to help me

quick dust
alpine cove
#

np

#

post your actual question

full valley
#

How would I be able to record audio in voice channels through a bot?

slate swan
full valley
#

damn

full valley
slate swan
#

none of that is able to record audio

naive briar
#

They really do hate pycord in here

slate swan
#

thats just vc channel related stuff and playing audio

slate swan
full valley
#

Alright I'll guess ill make it in js

#

thanks

naive briar
slate swan
hollow agate
#

I currently have this code: ```py
class AnswerQuestion(discord.ui.Modal, title='Give a Quote'):

answer = discord.ui.TextInput(
    label='Response',
    placeholder='What is your response?',
    max_length=2000,
)

async def on_submit(self, interaction: discord.Interaction):
    db = await aiosqlite.connect('database.db')
    cursor = await db.execute('SELECT * FROM questions WHERE question_message_id=?', (interaction.message.id, ))
    rows = await cursor.fetchone()
    freelancer = interaction.client.get_user(rows[1])
    embed = discord.Embed(title="New Response!",
                        description=f"Your question for {interaction.user.mention}'s project has been answered! \n\n{self.answer.value}",
                        color=discord.Color.orange())
    embed.set_footer(text=interaction.user, icon_url=interaction.user.avatar.url)
    embed.timestamp = datetime.now()
    await freelancer.send(embed=embed)
    for item in self.children:
        item.disabled = True
    await interaction.message.edit(view=self)
    await interaction.response.send_message("Successfully answered their question!", ephemeral=True)
    await db.execute('DELETE FROM questions WHERE question_message_id=?', (interaction.message.id, ))
    await db.commit()
    await db.close()``` My question lies in the ```py
    for item in self.children:
        item.disabled = True
    await interaction.message.edit(view=self)``` section. How could I disable the button that opens the modal? I cannot use what I currently have as `self` is defined as the Modal and not the button's stuff... This is how I send the Modal via the button: Opening the modal's code is: ```py

class AnswerQuestions(discord.ui.View):
def init(self):
super().init(timeout=None)

@discord.ui.button(emoji='📨', label='Reply', style=discord.ButtonStyle.grey, custom_id='questions:1')
async def reply(self, interaction: discord.Interaction, button: discord.ui.Button):
    await interaction.response.send_modal(AnswerQuestion())```
slate swan
#

is this dpy?

naive briar
#

Seems like

hollow agate
#

It is, yes.

slate swan
#

i mean since ur sending a modal

#

inside the button. use bot.wait_for for modal submit then disable button there

#

idfk i don't use view's for reasons like this. does dpy have "low level components"?

hollow agate
#

That would result in me not being able to have a persistent button

slate swan
#

otherwise you will need to find a way to get the component after submitting the modal

hollow agate
#

Yeah, I've been trying to get it via a message ID (I'm storing everything anyways), so I'm not sure

hollow agate
slate swan
#

oh ye true

hollow agate
#

I'm just super lost on what I can try that I haven't tried already 😂

slate swan
#

a janky way would be to use asyncio.sleep

naive briar
#

!d discord.ui.Modal.on_submit

unkempt canyonBOT
#

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

Called when the modal is submitted.
slate swan
#

in the button callback and set it to 5 mins. i think thats timeout limit for modals?

hollow agate
#

I don't think Modals have a timeout

slate swan
#

by default no

naive briar
slate swan
#

but you can set it.

hollow agate
#

Ahh, gotcha

topaz helm
#

does anyone have the removerole order? dm me pls

supple thorn
topaz helm
#

remove role

#

i have a give role

#

i need remove role

mighty pilot
#

By "I figured it out" I mean I asked here and played around with the answers people gave me until something finally worked

mighty pilot
#

i put that inside the code for my button and it disables the button after interaction

slate swan
#

guys whats the command to do that if a mod to action like mutes a member it will send the action in a channel ?

#

!d action

unkempt canyonBOT
slate swan
#

ok isnt that

slate swan
#

from inside the modal view

mighty pilot
#

thought he was trying to disable the button that creates the modal?

slate swan
#

yea after it is submitted

#

the first time

mighty pilot
#

oh he wants the button disabled after the modal is submitted not after the button is pushed?

slate swan
#

yeah cause what if the user clicks the button and doesn't actual send the modal, then they no longer have access to the button

mighty pilot
#

then theyd have to pop up another button lol Idkchu but yea i see

#

so could you pass the interaction into the modal with interaction: discord.Interaction then specify self.interaction = interaction in the modal and use self.interaction.followup.edit_message() inside the modal response?

slate swan
#

how would u pass interaction into the modal tho? you can't pass anything into .send_modal

#

guys how do i tag the action member

#

like the member that used to command

#

mute, so how do i get the moderator

#

author.mention

#

thanks!

mighty pilot
#

the way i passed a message interaction into my view was in the send command. so send_modal(AnswerQuestion(myview))?

slate swan
#

huh. .send_modal only takes a modal object

#

what u can do is. somehow store the id of the message containing the button and after the modal is submitted use View.from_message

mighty pilot
#

wish i had more time to try it out for myself but i gotta head to work. seems like there should be a way to pass it through without needing to store it

slate swan
#

this is why I don't like views at all lol

mighty pilot
#

yea theyre tricky thats for sure

slate swan
#

disnake has low level components where

@Cog.listener()
async def on_button_click(self, inter: disnake.MessageInteraction):
    if inter.component.custom_id == "asfdasf":
    ....
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'
whatt

mighty pilot
#

yea ive noticed that disnake tends to make shit easy for people lol

slate swan
#
@bot.command()
async def mute(ctx, member: discord.Member = None, time = None, *, reason='No reason!'):
  channel = bot.get_channel(1035829526766293043)
  if member is None:
    await ctx.send("Please mention the member you want to mute")
    return
  if member == ctx.message.author:
    await ctx.send("You cant mute yourself!")
    return 
  if time is None:
    await ctx.send("Please put the time!")
    return
  time = humanfriendly.parse_timespan(time)
  await member.edit(timed_out_until=discord.utils.utcnow()+datetime.timedelta(seconds=time))
  await ctx.send(f"{member.mention} Got muted\n Reason: {reason}")
  embed = discord.Embed(title="Member Muted", description=f"**Muted:** \n{member.mention}({member.name}) \n **Moderator:** \n {author.mention}({author.name})\n **Time:** \n {time}\n **Reason:**\n {reason}", color=0x1d2a3d)
  embed.set_thumbnail(url=ctx.member.avatar)
  embed.set_footer(text=f"Requested by {ctx.author.name}", icon_url=ctx.member.avatar)

  await ctx.channel.send(embed=embed)```

```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'
slate swan
#

no

mighty pilot
#

lmfao

slate swan
#

typo but datetime.timedelta not datetime.datetime.timedelta

slate swan
mighty pilot
#

how did you import it?

slate swan
#

did u import datetime from datetime?

slate swan
#

thats why

#

importing like that ur doing datetime.datetime.timedelta

#

so what do i do

#

from timedelta import datetime

#

no lol

#

remove ur import or

from datetime import datetime, timedelta
discord.utils.utcnow()+timedelta(seconds=time)
#

does anyone wanna make a bot together or am i going to make 1 alone 🥲

#

quack

glad cradle
slate swan
mighty pilot
#

Mod bots can be pretty labor intensive

slate swan
mighty pilot
#

Lots of lines of code

#

Depending on what you want it to do

slate swan
mighty pilot
#

I mean sure it always could be long if you make it do a lot. But there's a lot of moderation to be done in a server

slate swan
#

¯_(ツ)_/¯

#

at this point i wouldn't even make a mod bot, discord's automod taking over tbh.

mighty pilot
#

True. I hope they do it justice

mighty pilot
#

My shortest one is like 50 lines aside from a dict. Just posts a random fact every day

slate swan
#

music denied

#

🤣

slate swan
mighty pilot
#

I've already made a pretty intense level bot

slate swan
#

¯_(ツ)_/¯

#

im bored ¯_(ツ)_/¯

glad cradle
#

contribute to a library development 🙂

#

it's funny

slate swan
mighty pilot
#

You could make cogs for something like redbot

slate swan
#

🤣

slate swan
#

what

#

you don't need to learn cogs, thats just basic python

slate swan
#

you create a subclass of commands.Cog with command objects inside it

slate swan
slate swan
#

why do i hate this

#

that icon sux

slate swan
#

cuz ur new in the server

slate swan
glad cradle
#

L

mighty pilot
slate swan
#

whos ffzz

glad cradle
slate swan
slate swan
slate swan
#

they can access everything in the opened folder

#

including your token, if you have any

slate swan
#

idc if it get used

glad cradle
# slate swan how

Well, you upload your Bot code and contributors that wants to contribute will opens pull requests (they'll clone your repo and modify your Bot code locally) but it's a little bit complex because you need some rules and checks (and idk if non premium user can have checks, maybe they're only for teams)

slate swan
#

anyone can use checks using github workflows

glad cradle
mighty pilot
slate swan
#

ill use my friends account :~troll:

#
@bot.command()
async def mute(ctx, member: discord.Member = None, time = None, *, reason='No reason!'):
  channel = bot.get_channel(1035829526766293043)
  if member is None:
    await ctx.send("Please mention the member you want to mute")
    return
  if member == ctx.message.author:
    await ctx.send("You cant mute yourself!")
    return 
  if time is None:
    await ctx.send("Please put the time!")
    return
  time = humanfriendly.parse_timespan(time)
  await member.edit(timed_out_until=discord.utils.utcnow()+timedelta(seconds=time))
  await ctx.send(f"{member.mention} Got muted\n Reason: {reason}")
  embed = discord.Embed(title="Member Muted", description=f"**Muted:** \n{member.mention}({member.name}) \n **Moderator:** \n {ctx.author.mention}({ctx.author.name})\n **Time:** \n {time}\n **Reason:**\n {reason}", color=0x1d2a3d)
  embed.set_thumbnail(url=ctx.author.avatar)
  embed.set_footer(text=f"Requested by {ctx.author.name}", icon_url=ctx.author.avatar)

  await ctx.channel.send(embed=embed)```

and its sending the embed in the currect channel and not the channel i did   channel = bot.get_channel(1035829526766293043)
#

channel.send , not ctx.channel.send

#

remove the ctx

#

ohh

#

my bad lol thanks!

#

@slate swan oh hi

slate swan
#
@bot.command()
async def mute(ctx, member: discord.Member = None, time: int = None, *, reason='No reason!'):
  channel = bot.get_channel(1035829526766293043)
  ETA = int(time.time() + {time})
  if member is None:
    await ctx.send("Please mention the member you want to mute")
    return
  if member == ctx.message.author:
    await ctx.send("You cant mute yourself!")
    return 
  if time is None:
    await ctx.send("Please put the time!")
    return
  time = humanfriendly.parse_timespan(time)
  await member.edit(timed_out_until=discord.utils.utcnow()+timedelta(seconds=time))
  await ctx.send(f"{member.mention} Got muted\n Reason: {reason}")
  embed = discord.Embed(title="Member Muted", description=f"**Muted:** \n{member.mention}({member.name}#{member.discriminator}) \n **Moderator:** \n {ctx.author.mention}({ctx.author.name}#{ctx.author.discriminator})\n **Time:** \n <t:{ETA}:R>\n **Reason:**\n {reason}", color=0x1d2a3d)
  embed.set_thumbnail(url=ctx.author.avatar)
  embed.set_footer(text=f"Requested by {ctx.author.name}", icon_url=ctx.author.avatar)

  await channel.send(embed=embed)```

```discord.ext.commands.errors.BadArgument: Converting to "int" failed for parameter "time".```
#

the time that user provided wasnt an integer

#

i did !mute the mention and 1m

naive briar
#

That isn't an integer

slate swan
#

1m aint an integer

#

so what do i do

vale wing
slate swan
#

oh thanks

#

NameError: name 'Converter' is not defined

vale wing
#

Import it 🤓

slate swan
vale wing
#

import Converter the what

slate swan
#

ImportError: cannot import name 'Converter' from 'discord' (C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord_init_.py)

vale wing
#

What about paying more attention to imports that are in my code

slate swan
#

discord.ext.commands.Convertor

slate swan
vale wing
#

Yk what

slate swan
#

class TimeConverter(discord.ext.commands.Convertor):

vale wing
#

!pypi parsedatetime or smth

unkempt canyonBOT
vale wing
#

I forgor the lib

slate swan
vale wing
#

@slate swan ^

#

It's easier for you to use

slate swan
#

oh thanks!

glad thicket
#

no idea

#

hmm....

#

I have no idea

#

I think you may have to ask in the discord.py server

mighty pilot
#

Are you trying to make it happen all at once? If so you'll have to loop to make it go back over your if statements

#

Or are you triggering it twice

slate swan
#
@bot.command()
async def mute(ctx, member: discord.Member = None, time: str = None, *, reason='No reason!'):
  channel = bot.get_channel(1035829526766293043)
  if member is None:
    await ctx.send("Please mention the member you want to mute")
    return
  if member == ctx.message.author:
    await ctx.send("You cant mute yourself!")
    return 
  if time is None:
    await ctx.send("Please put the time!")
    return
  time = humanfriendly.parse_timespan(time)
  epochEnd = pyTime.time() + time
  await member.edit(timed_out_until=discord.utils.utcnow()+timedelta(seconds=time))
  await ctx.send(f"{member.mention} Got muted\n Reason: {reason}")
  embed = discord.Embed(title="Member Muted", description=f"**Muted:** \n{member.mention}({member.name}#{member.discriminator}) \n **Moderator:** \n {ctx.author.mention}({ctx.author.name}#{ctx.author.discriminator})\n **Time:** \n <t:{epochEnd}:R>\n **Reason:**\n {reason}", color=0x1d2a3d)
  embed.set_thumbnail(url=ctx.author.avatar)
  embed.set_footer(text=f"Requested by {ctx.author.name}", icon_url=ctx.author.avatar```
naive briar
#

What's the problem

#

Not everyone can just understand your problem by saying why is it not working

mighty pilot
slate swan
slate swan
naive briar
#

I meant round the time

slate swan
#

!d discord.utils.format_dt use it

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

you'll just have to pass the datetime in

naive briar
#

Yeah, that's easier 🫠

slate swan
#

epochEnd = pyTime.datetime() + time

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.

slate swan
#

epochEnd = datetime.fromtimestamp(time.time())

#

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

#

time there is an float

#

not the time lib

#

so what do i do

slate swan
#

discord.ext.commands.errors.MemberNotFound: Member "shj" not found.

#

what can i write to help that

#

@message.error
async def message_error(ctx, error):
if isinstance(error, commands.MemberNotFound):
await ctx.send("Please mention a member!")

#

discord.ext.commands.errors.MemberNotFound: Member "sh" not found.

#

now it is sending it but shows an error

slate swan
naive briar
#

!d discord.TextChannel.purge

unkempt canyonBOT
#

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

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

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

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

Examples

Deleting bot’s messages...
naive briar
#

purge don't accept positional arguments

primal token
meager chasm
#

okimi use sm common sense they r obviously not talking about self 😆

primal token
#

I'm not okimii? I'm correcting the persons statement as self can be passed positionally and it's an argument in the method, no?

honest shoal
#

How do we receive voice

slate swan
slate swan
slate swan
# primal token what

?self can be passed if you use it like discord.TextChannel.purge(...) ( as a function)
but not if you use it as <a discord.TextChannel object>.purge(...) ( as method )

primal token
#

It still would be a method

#

No matter how you access it

slate swan
unkempt canyonBOT
#

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

<class 'function'> <class 'method'>
primal token
slate swan
#

ok

primal token
#

Going by the terms lol

slate swan
#

disnake doesnt have voice support either ( from when i checked it for last time )

glad cradle
#

It doesn't exist yet

glad cradle
primal token
#

Hi snipy, long time no see👋

slate swan
alpine cove
alpine cove
#

bruz

alpine cove
slate swan
slate swan
alpine cove
#

I thought I'd use the opportunity

slate swan
#

i wanna do that if a member writes the command and the name it will send to the staff channel and will add a reaction of vi and x which thats what it is doing but how do i do that if a staff member clicks on vi it will change the name of the member to the name he chooses, and if on x it will send to the member that the name didnt approve?

@bot.command(aliases=["Name"])
async def name(ctx, name: str = None):
    Cha = bot.get_channel(695217470641799218)
    embed=discord.Embed(title="שינוי שם", description=f"{ctx.author.mention} רוצה לשנות את השם ל {name} ! מאשרים?")
    if name is None:
        return await ctx.send("בבקשה תציין שם !")
    else:
        await ctx.send("השם נשלח בהצלחה, נעדכן אותך!")
    moji = await Cha.send(embed=embed)
    await moji.add_reaction("✅")
    await moji.add_reaction("❌")```
silver tendon
#

Where in these commands should be located json.dump?

async def open_acc(user):
    users = await get_bank()

    if user.bot is True:
        return
    if str(user.id) in users:
        return False
    else:
        users[str(user.id)] = {}
        users[str(user.id)]["wallet"] = 100
    write_json("bank.json", users)
    return True
                

async def get_bank():
    users = load_json("bank.json")
    return users
upbeat otter
# slate swan i wanna do that if a member writes the command and the name it will send to the ...

you will have to store the message id along with the member id who requested the access to changing the name. you can use the on_raw_reaction_add event to check when a reaction is added to a message (You will need intents for this which are enabled in the default intents) . You can then check the message id with your stored ids and if there is a good match then you can do further processing

slate swan
alpine cove
#

I'm bad at structuring things

rustic onyx
#

!e


try:
  1 / 0
except ZeroDivisionError as error:
  if error == ZeroDivisionError:
    print("a")
unkempt canyonBOT
#

@rustic onyx :warning: Your 3.11 eval job has completed with return code 0.

[No output]
primal token
#

For things like that you would use isinstance

unkempt canyonBOT
#

@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.

False
cloud dawn
#

!e ```py
int = 1
print(1 == int)

unkempt canyonBOT
#

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

True
primal token
#

👽

naive briar
#

True

slate swan
#
def convert(time):
    pos = ["s", "m", "h", "d"]

    time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d": 86400}

    unit = time[-1]

    if unit not in pos:
        return -1
    try:
        val = int(time[:-1])
    except:
        return -2
    return val * time_dict[unit]




@bot.tree.command(name="giveaway")
@app_commands.describe(giveaway_time = "What time should the giveaway end? 1s/1m/1h/1d")
@app_commands.describe(prize = "What the prize should be?")
async def create(interaction: discord.Interaction,prize: str, giveaway_time: str):
    time=convert(giveaway_time)
    date=datetime.now() + timedelta(seconds=time)
    utc_time= calendar.timegm(date.utctimetuple())
    giveawayEmbed=discord.Embed(title=f"🎉 **{prize}** 🎉",description=f"> **Ends:** <t:{utc_time}:R>\n"
                                                                        f"> **Hosted By: {interaction.user.mention}")
    msg=await interaction.channel.send(embed=giveawayEmbed)
    await interaction.response.send_message(f"Successfully created giveaway in {interaction.channel}!", ephemeral=True)
    await msg.add_reaction("🎉")
    await asyncio.sleep(time)
    giveawaymsg=await interaction.channel.fetch_message(msg.id)
    users= await giveawaymsg.reactions[0].users().flatten()
    users.pop(users.index(bot.user))
    winner=random.choice(users)
    endEmbed=discord.Embed(title=f"🎉 **{prize}** 🎉",description=f"> **Ends:** <t:{utc_time}:R>\n"
                                                                        f"> **Hosted By:** {interaction.user.mention}\n"
                                                                   f"> **Winner:** {winner.mention}")
    await giveawaymsg.edit(embed=endEmbed)
    await giveawaymsg.reply(f"🎉 **Congratulations {winner.mention}!** 🎉")```
and when i try to make the time 1m it shows 2 hours
#

and then after a couple of mins it shows that error
discord.app_commands.errors.CommandInvokeError: Command 'giveaway' raised an exception: AttributeError: 'async_generator' object has no attribute 'flatten'

cloud dawn
#
users = [user async for user in (await giveawaymsg.reactions)[0].users()].flatten()
#

Aka I don't recommend using await like this.

slate swan
#

.flatten is no longer a thing

primal token
#

and you placed it incorrectly

slate swan
#

discord.app_commands.errors.CommandInvokeError: Command 'giveaway' raised an exception: TypeError: object list can't be used in 'await' expression

primal token
cloud dawn
slate swan
slate swan
#

discord.app_commands.errors.CommandInvokeError: Command 'giveaway' raised an exception: IndexError: list index out of range

primal token
#

Theres no reactions

slate swan
#

yup

#

but it still shows 2 hours

cloud dawn
#

I actually made something like this with time and I just forced the user to input a ranged int (0, 86400) and let the choose the prefix like days, minutes etc and if it is over a year convert it to just 1 year.

#
    @command(name="mute", description="Mute a certain member.")
    @describe(
        member="The member that is going to be muted.",
        length="Amount of time to mute the member.",
        unit="Unit of time.",
        reason="Why this member is getting muted."
    )
    @choices(unit=[
        Choice(name="Days", value=86400),
        Choice(name="Hours", value=3600),
        Choice(name="Minutes", value=60),
        Choice(name="Seconds", value=1)
    ])
    async def moderation_mute(
            self, interaction: Interaction,
            member: Member,
            length: Range[int, 1, 2419200],
            unit: Choice[int],
            reason: str = "No reason specified"
    ) -> None:
        second_amount = sec if (sec := length*unit.value) < 2419200 else 2419200
        dt = datetime.now().astimezone() + timedelta(seconds=second_amount)

        await member.timeout(dt, reason=reason)
        await interaction.response.send_message(
            f":ok_hand: Muted {member.mention} for `{reason}` until <t:{int(dt.timestamp())}:F>"
        )
slate swan
#

How i can update my discord bot

cloud dawn
hollow gazelle
#

i need help

#

how do i make my bot give someone a role after they do a command

#
 @bot.command()
async def register(ctx):
    embed = discord.Embed(
        description=
        f"**You Have __Successfully__ Registered As {ctx.author.mention}\n\nHave Fun Playing And Good Luck.**",color=0xfc0303)
    await ctx.send(embed=embed)```
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.
hollow gazelle
#

do i put role name await add_roles(*here, reason=None, atomic=True)

#
@bot.command()
async def register(ctx):
    embed = discord.Embed(
        description=
        f"**You Have __Successfully__ Registered As {ctx.author.mention}\n\nHave Fun Playing And Good Luck.**",color=0xfc0303)
     await add_roles(*roles, reason=None, atomic=True)
     await ctx.send(embed=embed)```
#
@bot.command()
async def register(ctx):
    embed = discord.Embed(
        description=
        f"**You Have __Successfully__ Registered As {ctx.author.mention}\n\nHave Fun Playing And Good Luck.**",color=0xfc0303)
     await add_roles(*roles, reason=None, atomic=True)
     await ctx.send(embed=embed)```
#

like that?

sick birch
#

You pass in the role you want to add

#

The role object not the name

hollow gazelle
#

how sorry for bothering im new to python

#
@bot.command()
async def register(ctx):
    embed = discord.Embed(
        description=
        f"**You Have __Successfully__ Registered As {ctx.author.mention}\n\nHave Fun Playing And Good Luck.**",color=0xfc0303)
     await add_roles(community, reason=None, atomic=True)
     await ctx.send(embed=embed)```
#

like this?

#

!d

unkempt canyonBOT
mighty pilot
#

You have to use get to get the role then use the role object not just the name

hollow gazelle
#

can u give exapmple

naive briar
#

Any object with id property works as far as I know

hollow gazelle
#

so id = idhere

#
@bot.command()
async def register(ctx):
    embed = discord.Embed(
        description=
        f"**You Have __Successfully__ Registered As {ctx.author.mention}\n\nHave Fun Playing And Good Luck.**",color=0xfc0303)
  await add_roles(name=community, reason=None, atomic=True)
    await ctx.send(embed=embed)```
mighty pilot
#

That's an indentation error. Fix your indents

hollow gazelle
naive briar
#

That's a familiar code highlight colours

hollow gazelle
#

HUH

balmy idol
#

VSC

hollow gazelle
#

no replit

#

im at school lol

balmy idol
#

Oh ok

hollow gazelle
#

how do i fix the indent

#

its not wroking

#

ive tried and tried

balmy idol
#

What is the error

hollow gazelle
naive briar
hollow gazelle
#
@bot.command()
async def register(ctx):
    embed = discord.Embed(
        description=
        f"**You Have __Successfully__ Registered As {ctx.author.mention}\n\nHave Fun Playing And Good Luck.**",color=0xfc0303)
  await add_roles(name=community, reason=None, atomic=True)
    await ctx.send(embed=embed)```
hollow gazelle
#

got that now

cold burrow
#

Hi I wrote this code back in 2017

string = [k,a,b,c,d,e,f,t,g]
for z in string:
    await client.edit_message(message,z)

This doesnt work anymore so after reading the documentation i tried this:

string = [k, a, b, c, d, e, f, t, g]
for z in string:
    await message.edit(z)

but i get the error
TypeError: edit() takes 1 positional argument but 2 were given

#

anyone know why ?

hollow gazelle
#

How do I fix

hollow gazelle
#

@naive briar can u help when u get a chance

cold burrow
grand willow
hollow gazelle
#

Ok

#

But where I put the roller it adds

#

Or above it

grand willow
hollow gazelle
#

How do I make it so It gives them a role I want

sick birch
hollow gazelle
#

Yes I have the Id for the role

sick birch
unkempt canyonBOT
#

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

Changed in version 2.0: `role_id` parameter is now positional-only.
hollow gazelle
#

Do I put it above or somthing

grand willow
#

Above giving the role yes

hollow gazelle
#

Ok

slate swan
hollow gazelle
hollow gazelle
glad cradle
fading dirge
#

does someone know why my bot cant send embeds? It doesnt show up any errors

glad cradle
hollow gazelle
#

how do i get a guild object

vale wing
hollow gazelle
#

pretty much not copying pasting everything i wrote the whole code to this bot just stuggleing with a few things

glad cradle
# hollow gazelle how do i get a guild object

ctx.guild.get_role(role_id) to get a role from the guild where the command was run, if you want to get a role from another guild where your Bot is in you need to get/fetch the guild with the Bot object

hollow gazelle
#

ok

#

thanks

vale wing
#

Well that thing is not really dpy related

#

It's more like functions related

hollow gazelle
#

but ok

vale wing
#

And that's programming term you gotta be familiar with to work with dpy

hollow gazelle
#

thats what i have down

hollow gazelle
vale wing
#

What python knowledge you got

#

You basically can't learn it if you don't know how functions work, because dpy is literally based on functions and OOP

hollow gazelle
#

nvm

#

i dont got it

grand willow
#

Then add role between the () in add_roles

shadow vigil
hollow gazelle
grand willow
hollow gazelle
#

do i put the id or the role name

shadow vigil
#

the id

grand willow
#

add role = before ctx.guild.get_role(103...

hollow gazelle
grand willow
#

role = ctx.guild....

hollow gazelle
#

ohhh

glad cradle
#

💀

grand willow
hollow gazelle
#

oops

glad cradle
#

role is not a keyword argument

shadow vigil
#

lmao

glad cradle
#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "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.
glad cradle
#

and you don't need to get the full role object, you can use discord.Object

#

!d discord.Object

unkempt canyonBOT
#

class discord.Object(id, *, type=...)```
Represents a generic Discord object.

The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.

There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.

x == y Checks if two objects are equal.

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

hash(x) Returns the object’s hash.
hollow gazelle
#

huhhhhhhhh

#

im just lost now

shadow vigil
hollow gazelle
#

ik that

#

but idk what to put now bc he said i cant use what nuke told me

#

says ctx undefind

shadow vigil
hollow gazelle
#

no the error is that

shadow vigil
hollow gazelle
#

wait

#

it is bc its not starting my bot mb

shadow vigil
#

python is the lang not the ide

grand willow
hollow gazelle
#

ok

#

still says it

grand willow
#

Between the ()

hollow gazelle
#

ik

shadow vigil
hollow gazelle
shadow vigil
shadow vigil
shadow vigil
hollow gazelle
#

huh

grand willow
# hollow gazelle

Add the role = ... into the function instead of ctx.guild.get_role() that u already have

fading dirge
#

why my bot does not send the embed?

shadow vigil
shadow vigil
fading dirge
shadow vigil
#

if the console is empty than the cmd or event did even started

fading dirge
shadow vigil
shadow vigil
fading dirge
#

ok

shadow vigil
#

or/and put your bot in debugging mode and watch the logs

fading dirge
#

the main porpoise is to verify the list, if the object is not in the list, will raise the error and send an embed helping how to use the command properly

#

but it doesnt make sense why cant send

shadow vigil
#

wait ignore my message

fading dirge
#

hm

naive briar
fading dirge
naive briar
fading dirge
#

sure, I have

shadow vigil
fading dirge
#

its on my main file, not the cog

shadow vigil
fading dirge
#

the problem is only with the embed, because i tried to replace the embed only with a phrase, and worked

mighty pilot
#

Does the command work at all or just not throw the error

fading dirge
#

when i removed the embed, the message was send

#

the problem is with the embed, only

#

do I need to import something specific?

naive briar
#

!d discord.Embed

unkempt canyonBOT
#

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

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

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

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
shadow vigil
naive briar
#

I don't think the Embed object takes the name kwarg pithink

fading dirge
#

I even coppied an old embed from other project

shadow vigil
mighty pilot
#

Try taking the name off the embed. Did you mean title instead?

fading dirge
naive briar
#

He probably have an error handler that ignores it if the error doesn't show

fading dirge
#

no, it still doesnt work

mighty pilot
#

Hmm

naive briar
#

!d discord.Embed.set_footer

#

Hmmmm

#

Weird

fading dirge
#

yeah

shadow vigil
# fading dirge

okay try putting discord.py in debugging mode and it will say if trys to send embed i don't remember how exactly but it won't hurt if you tried

#

i think its bot.run(TOKEN,debug=1)

mighty pilot
#

How do you set debug? Never knew that was a thing

#

Oh nice

fading dirge
#

ok

shadow vigil
mighty pilot
shadow vigil
#

!d discord.ext.commands.Bot.run

unkempt canyonBOT
#

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

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

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

Warning

This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
fading dirge
mighty pilot
#

Rip

naive briar
#

!d discord.ext.commands.Bot.run

unkempt canyonBOT
#

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

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

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

Warning

This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
shadow vigil
fading dirge
#

must be log handler

shadow vigil
#

yeah, its log handler i think i got confuse with another library

#

;-;

fading dirge
#

log_handler = True?

shadow vigil
fading dirge
#

ok

shadow vigil
#

hold sec

fading dirge
#

i know, look

shadow vigil
#
import logging,sys
handler = logging.StreamHandler(sys.stdout)
#code
...
bot.run(TOKEN,log_handler=handler)
shadow vigil
# fading dirge

stream handler is better, cuz you don't need to save the logs

fading dirge
#

ok thnks

fading dirge
#

client.start doesnt have log_handler, i dont think so

#

and client.run is not a coroutine

fading dirge
#

at least that is what i searched online, because when trying to use cog, it said that i must use await

white citrus
#
 f"> **Last Archive:** '<t:{int(s_channel.archive_timestamp.timestamp())}:F>' if '<t:{int(s_channel.archive_timestamp.timestamp())}:F>' else 'Not archived'}\n\n"
fading dirge
white citrus
fading dirge
#
f"> **Last Archive:** "<t:{int(s_channel.archive_timestamp.timestamp())}:F>"if "<t:{int(s_channel.archive_timestamp.timestamp())}:F>" else "Not archived"}\n\n"
#

@white citrus

mighty pilot
#

It says single close brace

fading dirge
#

know i think that the problem is with the cog

#

i will try also printing something at the console after the embed

white citrus
fading dirge
#

@shadow vigil I might have figured out

shadow vigil
#

what was it?

fading dirge
#

look, there is no ctx parameter

mighty pilot
fading dirge
#

prob is that

slate swan
shadow vigil
fading dirge
#

context

#

to send the message

#

oh forgot

shadow vigil
fading dirge
#

there is, at the beginning of the handler

white citrus
#

if and else is not in the f string how can i fix that

shadow vigil
fading dirge
#

i dont know 🤓

#

really

#

oh sure, worked now

#

i guess the problem was in the color

shadow vigil
#

lol ik, no sm

cursive gull
#

hey im making a bot that doesn't do anything he just lives and i need to him be online 24/7 also he has no code or anything like that theres a way to make this? free

naive briar
glad cradle
mighty pilot
#

There will be periods of 2-3 minutes of downtime throughout the day though as I'm currently having weird internet outages

drifting cypress
#

hello , i'm having a little problem:

await interaction.response.send_message("pong",components=[Button(label="Hey there!"), Button(label="Hi!")])

and it says "NameError: name 'Button' is not defined"
what should i import to get the button method ?
(tried google but haven't found any aswers)

naive briar
#

From the discord.ui

#

!d discord.ui.Button

unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.

New in version 2.0.
drifting cypress
hollow gazelle
#

how do i make it so u can only use the command in one channel?

slate swan
#

can someone help me with something

hollow gazelle
#

what is it

slate swan
#
try:
  name = input("\033[31mClick any key to return to menu")
except KeyboardInterrupt:
  print(x)
  time.sleep(5)``` whenever i use this it just closes the application
#

i dont know why

hollow gazelle
#

do u open it in cmd or vsc to see the error

slate swan
#

cmd

hollow gazelle
#

no error?

slate swan
#

no error

hollow gazelle
#

hmm

slate swan
#

just this it just closes it

hollow gazelle
#

did u click a key tho

#

bc kinda says except KeyboardInterrupt:

grand willow
hollow gazelle
#

kk

slate swan
#

but i just want it to reprint (X)

grand willow
slate swan
grand willow
#

Thats correct tho

slate swan
#

it just closes it when i click enter but i want it to reprint x

grand willow
#

Then add print(x) below input

slate swan
slate swan
#

I mean they should use it

slate swan
#

@grand willowwait but now it just makes the program stop

#

like it works but then after it prints the program closes

grand willow
#

Yes correct

slate swan
#

I want it to stay open so I can continue running commands inside it

grand willow
#

so u mean like

def main:
    input("Menu")
input("Press any Key to return to the Menu")
main()
slate swan
#

yes basically

#

but i cant add that into my code

grand willow
#

wdym

slate swan
#

bc this

#
\033[39m                        ╔═╗┌─┐┌\033[36m┐┌┬┌─┐
\033[39m                        ╚═╗│ ││\033[36m││││  
print(x)```
#

thats what x really equals

#

i don't see any issue with the value of an variable

#

!e ```py
x = """
\033[39m ╔═╗┌─┐┌\033[36m┐┌┬┌─┐
\033[39m ╚═╗│ ││\033[36m││││ """
print(x)

unkempt canyonBOT
#

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

001 | 
002 |                         ╔═╗┌─┐┌┐┌┬┌─┐
003 |                         ╚═╗│ ││││││  
slate swan
#

works like any other thing

#

Yeah ik

#

im doing this

  name = input("\033[31mClick any key to return to menu")
  os.system("cls")
  print(x)
except KeyboardInterrupt:
  time.sleep(5)``` so it should print x but also still let me use the cmd prompt but instead it just closes
#

so it works but soon as i enter another command it closes

grand willow
slate swan
#

well your code is completed why would it continue later

grand willow
#

The code ends there

slate swan
#

this is my full code right here

#
import sys
import os
import time

os.system("color")
os.system("cls")

x = """
\033[39m                        ╔═╗┌─┐┌\033[36m┐┌┬┌─┐
\033[39m                        ╚═╗│ ││\033[36m││││  
"""
print(x)


Info = """

"""


command = input('''
╔═[\033[39m\033[36m]
╚═➢ ''')


if command == '1':
   os.system ("cls")
   print(x)
   print(Info)




elif command == "":
    os.system ("cls")
    print(x)

elif command == "exit":
    exit()

try:
  name = input("\033[31mClick any key to return to menu")
  os.system("cls")
  print(x)
except KeyboardInterrupt:
  time.sleep()
#

so how do i make it return to print(x) and it still lets me run the command 1

#

@slate swan@grand willow

#

one possible solution is function recursion

#

but how is this related to a discord bot

#

im new so i dont know how

#

becuase im trying to make something

#

its a currency bot

#

so how do i do a function recursion

#

so can u help or no?

#

Hello guys how do i black list role from discord.py commands ?

slate swan
slate swan
#

just make commands moderator-only

#

depends on what you want though

sick birch
#

I'd honestly just add a global check

keen vault
slate swan
keen vault
#

okay, i'm having struggles with installing discord.py 2.0

#

i'm new to this and saw a youtube tutorial

#

he told me to put this in terminal, I've downloaded python and everything I need

slate swan
#

jusst use pip install discord.py it will install 2.0

keen vault
#

it says pip isn't recognised as an internal or external command, operable program or batch file

unkempt canyonBOT
#
Install packages with `python -m pip`

When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.

Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.

Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.

sick birch
#

just using pip is not recommended

keen vault
mighty pilot
#

Try pip3

#

You have installed pip?

keen vault
#

yes

mighty pilot
#

May need to correct your path to the pip package

keen vault
#

where do I find the pip package

mighty pilot
#

There's easy tutorials on the internet, that's going to probably be your best resource for that

slate swan
#

💀 just download get-pip.py and run it with python

hushed galleon
# keen vault

i would recommend installing 3.10 since some of discord.py's dependencies dont have prebuilt wheels for python 3.11 (yet), meaning you would have to additionally install 6 gigabyte C++ build tools to compile them

#

if you're getting the installer from python.org, look for 3.10.8 (latest) in the downloads page, and in the installer make sure pip is included with it

keen vault
#

Right, I will try to delete 3.11 and install 3.10 then

keen vault
hushed galleon
#

perhaps itd be better for you to click the recommended install instead, rather than touching any of the options

#

afterwards you'll get a py command that you can use in place of python, e.g. py -m pip install discord.py

keen vault
#

there's still no module named pip

hushed galleon
hollow agate
#

@keen vault try python3 -m pip install discord.py

#

If not, uninstall all your Python downloads and reinstall the newest version with pip

wanton pebble
#

or just convenient if you already know python

sick birch
wanton pebble
#

what i just said. sorry for not adding it to og message

sick birch
wanton pebble
#

hm. are there better ways to make discord bots?

mighty pilot
#

sooo i just discovered a new website

#

discord.bot is website

sick birch
wanton pebble
#

wtf is this

sick birch
#

Most wrappers have the same issue

wanton pebble
#

but arent bots becoming more fun now with like embeds and actual buttons and stuff

mighty pilot
#

lol fun to look at

wanton pebble
#

i enjoy the intuitiveness to it

sick birch
#

If you find it fun, and you've got the prerequisite and motivation, go for it!

wanton pebble
#

what are those bots usually coded in though?

sick birch
#

Though discord bots get dry after a while. I haven't done any in months

mighty pilot
#

i find it fun but im a weirdo. i yearn for knowledge

wanton pebble
#

just discord.py? or are there other languages and libraries out there

sick birch
#

Those are the 2 biggest competitors

mighty pilot
#

ive tried both, i prefer python

wanton pebble
#

now, unbiased, which one's more efficient and user-friendly

sick birch
sick birch
#

discord.JS is more "low level" (that is, closed to the API)

#

More control, less user friendliness

mighty pilot
sick birch
#

I generally dislike the discord bot market

mighty pilot
#

ive noticed a LOT of bots are kinda half made and their support servers arent much help

wanton pebble
#

mee6 sucks

#

mee6 is the worst bot

mighty pilot
#

like even the popular ones, if youre trying to do something one off with it they dont want to help because its not something they can copy paste from the chat above

wanton pebble
#

yeah

mighty pilot
#

ive been to yagpdb server countless times with a question and they tell me it cant be done, just for me to spend a weekend figuring it out on my own and it actually works

#

a big reason i started making and hosting my own stuff

wanton pebble
#

isnt yagpdb dedicated for like developers n stuff

#

and its super complicated to the average discord user to... calibrate? because of just how many options are given n stuff

mighty pilot
#

its a good free resource imo because they offer a lot of stuff without premium like custom commands with code and auto mod and stuff

slate swan
#

discord bots are in a dry spot right now until discord implements more features

#

we need select in modals, and better usage for the role select menus, etc...

mighty pilot
#

or more people need to get creative lol

slate swan
#

not really all the current select modals and UIs are so limited

mighty pilot
#

wym more usage for role select menus

slate swan
#

thats all it is, a full list of roles, members, etc. you can't specify or limit them.

mighty pilot
#

oh i see, like filters

#

reason i ask is my level bot features a split tree role assignment system

slate swan
#

yea exactly, imagine a filtered role select

unkempt canyonBOT
#

Hey @young pendant!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

young pendant
#

Can someone help me?

slate swan
#

!d discord.ext.commands.Bot.case_insensitive

unkempt canyonBOT
#

Whether the commands should be case insensitive. Defaults to False. This attribute does not carry over to groups. You must set it to every group if you require group commands to be case insensitive as well.

young pendant
#

@hollow agate Can you help me? KEKW

hollow agate
#

Sure

#

if self.roles_of_team1[guild_id] != [] and guild_id in self.team_roles1.keys():

#

There's something wrong with this, I can't read your code because it's literally impossible to

#

prolly an invalid id or some sorts

young pendant
#

hmm, weird

mighty pilot
#

is there a sub-subcommand in slash commands?

slate swan
#

nah there are sub groups tho

#

then a sub cmd of that group

mighty pilot
#

i found a workaround no need to dive into that tonight

slate swan
#

all i use is sub cmds anymore lol

little narwhal
#

i assume this is with hybrid_group?

mighty pilot
primal token
#

!d object.repr

unkempt canyonBOT
#

object.__repr__(self)```
Called by the [`repr()`](https://docs.python.org/3/library/functions.html#repr "repr") built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form `<...some useful description...>` should be returned. The return value must be a string object. If a class defines [`__repr__()`](https://docs.python.org/3/reference/datamodel.html#object.__repr__ "object.__repr__") but not [`__str__()`](https://docs.python.org/3/reference/datamodel.html#object.__str__ "object.__str__"), then [`__repr__()`](https://docs.python.org/3/reference/datamodel.html#object.__repr__ "object.__repr__") is also used when an “informal” string representation of instances of that class is required.

This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.
mighty pilot
#

idk why it returns that though.. even the docs say you should be able to use that to pull a user obj from reactions then mention that user. which you cant do with that repr

fading dirge
#

Does anyone here know how to use sqlite and wouldnt mind helping me?

mighty pilot
fading dirge
#

but its also for a discord bot, i dont know where the problem is

mighty pilot
#

i mean, idc where anything is discussed, but you may get better/quicker help there

primal token
fading dirge
#

how can I work with 2 arguments for a specific command to execute?

mighty pilot
#

if its being pulled as an object

fading dirge
#

it simply doesnt work

#

does not recognize both of the args

#

only the first

primal token
primal token
unkempt canyonBOT
#

@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.

[<Foo object!>, <Foo object!>, <Foo object!>, <Foo object!>, <Foo object!>, <Foo object!>, <Foo object!>, <Foo object!>, <Foo object!>, <Foo object!>, <Foo object!>]
mighty pilot
primal token
mighty pilot
#

its a list of 1 user so would i use result[0].mention?

primal token
#

Yep!

mighty pilot
#

thanks

primal token
#

Do know it can raise an error

mighty pilot
#

one thing at a time lol

primal token
alpine cove
#

it doesnt seem like ur awaiting your db call

fading dirge
alpine cove
#

ofc

fading dirge
#

oh

#

ok thks

alpine cove
#

use aiosqlite

primal token
#

Also, you shouldn't be using f-strings, it's bad practice

sick birch
#

sqlite3 is blocking which is bad so you'd want to use like asqlite or aiosqlite or something

alpine cove
#

it has the same syntax as sqlite

alpine cove
#

but apart from that yes you shoudlnt

#

*shouldnt

mighty pilot
primal token
slate swan
sick birch
#

it returns an async generator

#

not a list

mighty pilot
#

Yea I tried lol

#

Can confirm

slate swan
#

.flatten()

#

?

sick birch
#

i don't believe that exists on .users

slate swan
#

it should

primal token
#

no?

mighty pilot
#

Flatten isn't a thing there anymore

slate swan
#

dpy so shit im sorry

primal token
sick birch
#

thanks

mighty pilot
#

Big words I should know more about

primal token
#

!e

import asyncio


async def bar():
    yield 1

async def main():
    print(bar())

asyncio.run(main())
unkempt canyonBOT
#

@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.

<async_generator object bar at 0x7f0861c8a8d0>
mighty pilot
#

So async generator is the object but the need for the object is an iterator Sussott

alpine cove
#

but i'll raise if the gen is empty

sick birch
mighty pilot
sick birch
#

some wise dude once said if you can explain something to a child, then you've mastered it
or something like that idk i dont read

alpine cove
sick birch
#

clearly i have not mastered it :p

alpine cove
primal token
alpine cove
#

oh f fr?

#

pls end me

sick birch
#

fr on jah

alpine cove
#

I rarely use gens

mighty pilot
alpine cove
#

!e
myGen = (i for i in range(20))
print(myGen)
print(next(myGen))

unkempt canyonBOT
#

@alpine cove :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | <generator object <genexpr> at 0x7f2485d881e0>
002 | 0
primal token
#

?

mighty pilot
#

Off to bed. Jury duty starts bright and early pikawut5

#

Thanks again for the help

alpine cove
sick birch
primal token
alpine cove
#

yea u said it didnt

primal token
#

where

sick birch
alpine cove
#

lmfao

sick birch
#

mfw when then funny comes back to me once a month

alpine cove
#

at least admit your mistakes

primal token
#

I wont because I'm not incorrect?

alpine cove
#

I'm not here to help 5yr olds like you just forget it

sick birch
primal token
#

A generator can be an iterator not vice-versa, they're both different objects that have different behavior, saying

but i'll raise if the gen is empty

would be incorrect as it's a async iterator and not a generator as it doesnt implement certain methods making it a generator

alpine cove
alpine cove
primal token
#

There is!

alpine cove
#

or to be more precised there is no async gen

primal token
alpine cove
#

point taken

stone karma
#

you all have experience in different bots for runescape servers with eco and all that

sick birch
stone karma
south coyote
#

hey can somebody tell me how to piece this together?

@bot.tree.command(name='support')

async def support(interaction: Discord.Interaction):

@commands.has_role('verified')

async def create_channel(ctx):

    channel_name=(f"help--{ctx.author.name}")
    
    guild = ctx.guild
    
    existing_channel = discord.utils.get(guild.channels, name=channel_name)
    
    if not existing_channel:
        print(f'Creating a new channel: {channel_name}')
    
        await interaction.guild.create_text_channel(channel_name)
vocal snow
#

What are you trying to do

south coyote
#

create a channel

#

ive got the boilerplate in place

#

i think im crossing streams

vocal snow
#

Where's the code for that slash xommand

south coyote
#

hmmm

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


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


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

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


@bot.tree.command(name='support')

async def support(interaction: Discord.Interaction):

@commands.has_role('verified')

async def create_channel(ctx):

    channel_name=(f"help--{ctx.author.name}")
    
    guild = ctx.guild
    
    existing_channel = discord.utils.get(guild.channels, name=channel_name)
    
    if not existing_channel:
        print(f'Creating a new channel: {channel_name}')
    
        await interaction.guild.create_text_channel(channel_name)




@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.errors.CheckFailure):
        await ctx.send('You do not have the correct role for this command.')

#bot.run('...')
#

im trying to figure out what is missing and what is supposed to be taken out

#

ive been working on this all afternoon

#

so i need to put something after the async def support(interaction: Discord.Interaction):?

#

im trying to let users make a help channel that includes their name in the channel

naive briar
#

All I see are syntax errors

upbeat gust
south coyote
#
import discord
from discord import app_commands
from discord.ext import commands


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


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

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


@bot.tree.command(name='support')
@commands.has_role('verified')

async def create_channel(ctx):

        channel_name=(f"help--{ctx.author.name}")
    
        guild = ctx.guild
    
        existing_channel = discord.utils.get(guild.channels, name=channel_name)

async def support(interaction):
    if not existing_channel:
            print(f'Creating a new channel: {channel_name}')
    
    await interaction.guild.create_text_channel(channel_name)


@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.errors.CheckFailure):
        await ctx.send('You do not have the correct role for this command.')

#bot.run('...')
#

i changed it around no existing_channel and channel_name is lit up

#

yeah i know basic python

#

but how does that look so far

#

this runs

#

but im getting an error in the server when i try to invoke the command

upbeat gust
#

support doesn't have a decorator