#discord-bots

1 messages · Page 207 of 1

radiant bough
#

I think they are trying to add a member to a channel if channel name starts with ticket-

shell wing
#

maybe add print() statements after every await and all to see if the code is working or not

#

also ig it should just be ticket not ticket- cause - is just a visual component added by discord instead of spaces

slate swan
#

What do you want options to be?

#

Ah okay now i understood what is the point of this command

#

You could make argument options and accept different options separated by comma or so

#

Then split it in code

light violet
#
class signup(Modal, title="Sign Up"):
    username = TextInput(label="Enter Your New Username .", style=discord.TextStyle.short, required=True)
    password = TextInput(label="Enter Your Password .", style=discord.TextStyle.short, required=True)

    async def on_submit(self, interaction: discord.Interaction):
      username = self.children[0]
      print(username)
      password = self.children[1]
      print(password)
      if username in db["userreg"]:
        
        button1 = Button(label="Try Again.", style=discord.ButtonStyle.blurple)
        async def buttonSign_callback(interaction):
          if interaction.user.id!=interaction.author.id:
            return
          else:
            res=await interaction.response.send_modal(signup())
            view = View(timeout=60) 
            view.add_item(button1)
          await interaction.response.send_message(title="Sign Up.",description=f"This Username `{self.children[0]} already exists.`",view=view)
      else:
        dt = {"id": str(interaction.user.id),
              "password":password,
             }
        db["userreg"].append(username)
        db[f"{username} i"]= dt
        print(db[f"{username} i"])
        em=discord.Embed(title="Sign Up.",description="Success.")
        await interaction.response.send_message(embed=em)
        #reg(dt,username)
        return True```
#

Traceback (most recent call last): File "/home/runner/ShinyPastAssembly/venv/lib/python3.10/site-packages/discord/ui/modal.py", line 187, in _scheduled_task await self.on_submit(interaction) File "main.py", line 41, in on_submit db["userreg"].append(username) File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/_collections_abc.py", line 1123, in append self.insert(len(self), value) File "/home/runner/ShinyPastAssembly/venv/lib/python3.10/site-packages/replit/database/database.py", line 286, in insert self.on_mutate() File "/home/runner/ShinyPastAssembly/venv/lib/python3.10/site-packages/replit/database/database.py", line 256, in on_mutate self._on_mutate_handler(self.value) File "/home/runner/ShinyPastAssembly/venv/lib/python3.10/site-packages/replit/database/database.py", line 373, in cb db[k] = val File "/home/runner/ShinyPastAssembly/venv/lib/python3.10/site-packages/replit/database/database.py", line 491, in __setitem__ self.set(key, value) File "/home/runner/ShinyPastAssembly/venv/lib/python3.10/site-packages/replit/database/database.py", line 500, in set self.set_raw(key, _dumps(value)) File "/home/runner/ShinyPastAssembly/venv/lib/python3.10/site-packages/replit/database/database.py", line 56, in dumps return json.dumps(val, separators=(",", ":"), cls=DBJSONEncoder) File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/json/__init__.py", line 238, in dumps **kw).encode(obj) File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) ValueError: Circular reference detected

#

help pls

slate swan
#

!FOR

#

someone pls help?

naive briar
#

Not relevant to this channel, but okay

#

!d input

unkempt canyonBOT
#

input()``````py

input(prompt)```
If the *prompt* argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, [`EOFError`](https://docs.python.org/3/library/exceptions.html#EOFError "EOFError") is raised. Example:

```py
>>> s = input('--> ')  
--> Monty Python's Flying Circus
>>> s  
"Monty Python's Flying Circus"
```  If the [`readline`](https://docs.python.org/3/library/readline.html#module-readline "readline: GNU readline support for Python. (Unix)") module was loaded, then [`input()`](https://docs.python.org/3/library/functions.html#input "input") will use it to provide elaborate line editing and history features.

Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `builtins.input` with argument `prompt` before reading input...
slate swan
#

soooooooooooo

naive briar
#

This function returns the input as string, so just convert it to int

slate swan
#

wym

#

i did it but its like this

naive briar
#
X = int(input(...))
#

Are you familiar with Python

#

Well, I don't have to guess

slate swan
slate swan
#

this is what she told me to do:
The Israel Trail is a long walking route divided into 44 sections. Each section has a name.
Write a program that will record the name and length of each of the 44 sections. The program will print the names
The sections that are longer than 10 km. Also, the program will calculate the total length of the Israel Trail and print
This number.

thin raft
#

Can I make a parameter accept a file?

karmic nimbus
#

idk where the problem, it says indentation Error: outer level in line 39 how to fix it?

thin trout
#

how can i create a bot that sends twitch notifications when a live starts?

thin raft
#

best way to check errors

embed = discord.Embed(
  title = "This is a title",
  description = "Lorem ipsum dolor sit amet"
)

await ctx.send(
  ctx.author.mention,
  embed = embed
)
``` for example
thin raft
#

I think you could do smt with that, but instead of sending it on message send it when the stream starts
https://twitchio.dev/en/latest/

short ice
slate swan
#

This means that ctx.message is None

naive briar
#

There's only interaction with slash commands

#

!d discord.Interaction

unkempt canyonBOT
#

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

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

New in version 2.0.
short ice
naive briar
#

Yes, but I won't

slate swan
#

We wont write code for you

short ice
#

damn alr

woeful magnet
#

#bot.py
import os

import discord
from discord import utils
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
SERVER_ID = 1079627037163147294
CATEGORY_ID = 1079870065488441464

intents = discord.Intents().all()
client = discord.Client(intents=intents, partials=["CHANNEL"])

channels = {}

@client.event
async def on_ready():
print(f'{client.user} has connected to Discord')

@client.event
async def on_message(message):
server = client.get_guild(SERVER_ID)
category = server.get_channel(CATEGORY_ID)

if isinstance(message.channel, discord.DMChannel) and message.author != client.user:
print(message.content)
channel_name = f"{message.author.name}".lower().replace(" ", "-")

embed = discord.Embed(
  title = f"Message from {message.author.name}({message.author.id})",
  description = message.content,
  timestamp = message.created_at,
  color = 0x00ff00
)

existing_channel = utils.get(category.channels, name=channel_name)
if existing_channel:
  print(client.get_channel(existing_channel.id))
  await client.get_channel(existing_channel.id).send(embed=embed)
  # f"{message.author}:{message.content}"
else:  
  overwrites = {
    server.default_role: discord.PermissionOverwrite(read_messages=False),
    server.me: discord.PermissionOverwrite(read_messages=True)
  }
  # Insert DM channel into channels dictionary
  channels[channel_name] = message.channel
  
  channel = await category.create_text_channel(channel_name, overwrites = overwrites)
  await channel.send(embed=embed)

elif message.author.id == server.owner.id:
print(channels)
for x in channels.keys():
if message.channel.name == x:
print(message.channel)
await channels[x].send(f"{message.content}")

client.run(TOKEN, bot = False)

This is my code, whenever I run this code, I can see errors:

thin raft
#

!code

unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

thin raft
#

and

#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

thin raft
#

we don't help with discord self bots

karmic nimbus
#

is music bot break laws?

languid oxide
#

hi all

#

quick question. I made a "local" software with python and tkinter. And I also made a discord bot.
I would like to try to add discord login to my local app, so that I can then connect it to my discord bot
so that eventually I can type something in discord, and this software does an action

#

is anyone here available to help?

shrewd fjord
naive briar
#

Or any platform that doesn't allow it, really

#

If you're using an official API to stream the music then it's allowed, I guess

echo wasp
#

hola

#
    await setup(self)
TypeError: object NoneType can't be used in 'await' expression

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

Traceback (most recent call last):
  File "C:\Users\grand\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "E:\My_stuff\Discord bots\everything bot prod\bot.py", line 62, in on_ready
    await bot.load_extension("cogs.fun")
  File "C:\Users\grand\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
    await self._load_from_module_spec(spec, name)
  File "C:\Users\grand\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 952, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.fun' raised an error: TypeError: object NoneType can't be used in 'await' expression```
#

what did i do wrong?

echo wasp
#

but now it not working

unkempt mauve
echo wasp
unkempt mauve
echo wasp
#

without a @command.commands on it

unkempt mauve
#

bot.load_extension can only load commands

echo wasp
#

then why did it load my entire cog before using that

unkempt mauve
#

using os and asyncio

#

create a function

echo wasp
unkempt mauve
echo wasp
#

without an on_ready even

unkempt mauve
#

!d discord.ext.commands.Bot.load_extension

unkempt canyonBOT
#

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

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.

Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.11)").
echo wasp
#

setup point telling it what todo

unkempt mauve
#

what do you have in your main py

echo wasp
#

the main photo i sent

unkempt mauve
#

u need to make a function

echo wasp
#

by doing what

echo wasp
unkempt mauve
#
async def main():
  for filename in os.listdir('./cogs'): #import os
      if filename.endswith('.py'):
        await bot.load_extension(f'cogs.{filename[:-3]}')
  await bot.start('token')

asyncio.run(main()) #import asyncio```
#

that will load

slate swan
echo wasp
unkempt mauve
#

u need to send us the definition of the bot then

echo wasp
hushed galleon
slate swan
unkempt mauve
unkempt mauve
slate swan
#

pip install -U discord

echo wasp
unkempt mauve
echo wasp
hushed galleon
unkempt mauve
echo wasp
#

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

hushed galleon
#

in other words your on_ready is "suitably written" for discord.py 2.0, you're just not using 2.0

hushed galleon
#

well i guess its 2.2 now

hushed galleon
#

still getting the same nonetype error on load_extension?

hushed galleon
#

might want to try reinstalling it, i.e. pip install --force-reinstall discord.py

echo wasp
hushed galleon
#

oh hold on that error isnt* load_extension itself

#

oops, the actual error is that your setup() method isnt asynchronous

echo wasp
echo wasp
#

that would make sense why it didn't work

#

thanks

slate swan
#

im using nextcord and it isnt like this there its something new in discordpy?

#

that setup has to be async function

hushed galleon
#

iirc discord.py introduced it after they went back into development, hence why most of the forks dont do the same thing

shell wing
#
await interaction.response.send_message(content=f'Deleted **{amount}** messages with the reason: {reason}')```
#

and ig try removing len

unkempt mauve
shell wing
#

ig it depends on ur Bot's resources

unkempt mauve
shell wing
#

Get better resources ?

unkempt mauve
#

huh

shell wing
#

i mean honestly i never faced such issue(s), so i dont have much info about them

hushed galleon
#

bulk message deletion has been slow for a while i think, even right now it still takes several seconds and a whole lot longer for it to actually be deleted (my messages below should have disappeared)

#

other people seem to be reporting the same issue discord/discord-api-docs#5974

glad cradle
glad cradle
#

👍

plain pollen
#

real quick question, with discord.py, does cog_unload run automatically when the bot loading it stops existing, i.e. at the end of execution?

vale wing
#

It was like at the same time

languid oxide
#

hi all

#

I'm pretty depressed lol. yesterday I was doing pretty well, today every single tutorial I watch feels like aramaic

slate swan
#

Why does my button fail after 10 mins or so?

plain pollen
#

aah i see, thanks!

vital glacier
#
    @commands.command(
        name='inrole',
        aliases=['members'],
        usage='inrole',
        description=''
    )
    async def inrole(self, ctx, *, role: discord.Role):
        """View the users in a role"""
        
        await ctx.typing()
        embeds = []
        ret = []
        num = 0
        pagenum = 0
        for m in ctx.guild.members:
            if m in role.members:
                num += 1
                ret.append(f'**{num}.** {m.mention} ({m.id})')
                pages = [p for p in discord.utils.as_chunks(ret, 10)]
        for page in pages:
            pagenum += 1
            embeds.append(discord.Embed(
                color=color,
                title=f'Members with {role.name}',
                description="\n".join(page))
                .set_author(name=ctx.author.display_name, icon_url=ctx.author.display_avatar)
                .set_footer(text=f'Page {pagenum}/{len(pages)}')
                )
            if len(embeds) == 1:
                return await ctx.send(embed=embeds[0])
            else:
                pag = Paginator(self.bot, embeds, ctx, invoker=ctx.author.id)
                pag.add_button('prev', emoji='![previous](https://cdn.discordapp.com/emojis/1079740421078515772.webp?size=128 "previous")')
                pag.add_button('goto', emoji='![goto](https://cdn.discordapp.com/emojis/1079740417655963710.webp?size=128 "goto")')
                pag.add_button('next', emoji='![next](https://cdn.discordapp.com/emojis/1079740422722695220.webp?size=128 "next")')
                pag.add_button('delete', emoji='![x_cross](https://cdn.discordapp.com/emojis/1079740426577264681.webp?size=128 "x_cross")')
                await pag.start()

Anyone got an idea why this wont work?
It's not putting the paginator when the embeds are more than 1

unkempt canyonBOT
#

Hey @twilit veldt!

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

twilit veldt
#

Pleaseee Help me.. The Error, dont go away.. Here is the code, and the error:

Error:

2023-03-03 18:18:42 ERROR discord.ext.commands.bot Ignoring exception in command setchannel
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "d:\Python Scripts\countingbot.py", line 111, in setchannel
data = json.load(f)
^^^^^^^^^^^^
File "C:\AppData\Local\Programs\Python\Python311\Lib\json_init_.py", line 293, in load
return loads(fp.read(),
^^^^^^^^^^^^^^^^
File "C:\Users\AppData\Local\Programs\Python\Python311\Lib\json_init_.py", line 346, in loads
return _default_decoder.decode(s)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AppData\Local\Programs\Python\Python311\Lib\json\decoder.py", line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 14 (char 13)

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

Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Extra data: line 1 column 14 (char 13)

Code (Pastebin)

https://paste.pythondiscord.com/fasecosime

hushed galleon
#

JSONDecodeError: Extra data means the file had a properly formatted value, but there was more data beyond said value

#

in your case its most likely because you're using f.seek(0) to try overwriting the file but forgetting to truncate the existing data

#

id suggest just opening the file twice, once to read and once to write ```py
with open("file") as f:
data = json.load(f)

with open("file", "w") as f:
json.dump(data, f)```

hushed galleon
twilit veldt
slate swan
#

Wdym

#

I changed the timeout to None

hushed galleon
#

well i should ask first if you want your view to still work after a restart

hushed galleon
#

then on bot startup, you need to add the view instance using Client.add_view()

hushed galleon
slate swan
#

In addition, wouldnt the information be lost once the bot restarts so how can you save it?

hushed galleon
#

well send() sends a message, but add_view() is simply informing discord.py that there's a view that it should be receiving interactions from

slate swan
#

ohhh

#

hm, alr.

twilit veldt
twilit veldt
thin lake
#

Someone know how can i make my bot read another bots messages?

hushed galleon
hushed galleon
thin lake
hushed galleon
# slate swan In addition, wouldnt the information be lost once the bot restarts so how can yo...

if your view doesnt have any kind of dynamic data required during initialization then adding the view is fairly easy, e.g. ```py
class MyView(discord.ui.View):
@discord.ui.button(label="Hello world!", custom_id="hello-world")
async def on_click(self, interaction, button):
await interaction.response.send_message("Hello world!")

client = discord.Client(...)
client.add_view(MyView(timeout=None))
client.run(...)``` but when your view needs more information like the original user's ID, its up to you to choose how to store that data and retrieve it, for example inserting into a database and then retrieving it on startup to re-create the view instance

hushed galleon
hushed galleon
#

!paste and make sure you dont show your token

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.

thin lake
wanton current
#

this should error

hushed galleon
# twilit veldt Not really <:incident_unactioned:714223099645526026>

a file with "extra data" can look like this: {"channel_id": 2468, "last_count": 1234}234} ^ Extra data this is a typical issue when you forget to truncate the file before/after writing, but when you use open("file", "w") it does the truncation for you which ensures you wont have extra data when you dump your dictionary's contents into the file

runic whale
#

Hey all, forgive me if I'm in the wrong place, but seeing a ton of questions here...

Working on a discord bot that pulls a random row out of MySQL database via connection to Python, everything works perfectly, except the random part. Does anyone have any insight on possible routes I can take to troubleshoot this? Is there a way possibly to "refresh" the MySQL connection every time the query is run, or the bot is run? New to Python, so looking for knowledge, not just a quick fix. Thanks!

steep estuary
#

can I display custom emojis in discord.py button's label?

hushed galleon
# thin lake ok so basiclly i would make a helper bot for another bot that me and friends pla...

what williboy said, that is syntactically incorrect, but given your bot is spamming i presume you have written it like this: py @client.event async def on_message(message): if message.author.id == 571027211407196161: for word in raids_keywords: await message.channel.send(f'{message.mention.author}.') else: await message.channel.send('Nothing atm') remember what i said before?

the on_message event is fired for every message the bot can see
that means any message, from any channel, from anyone, including the bot's own messages too

#

also sending a bunch of messages in that for loop will get your bot ratelimited

thin lake
hushed galleon
hushed galleon
hushed galleon
#

dont have the .send("Nothing atm") in that else clause

unreal iron
#
@client.tree.command(name="test")
    async def test(interaction: discord.Interaction, id: str, message: str):
        user = client.get_user(int(id))
        await user.send(message)

Hello this is my code for a slash command where you put someones id and message, and the bot will send the message to the user. Is there a way that I instead of typing someones id I can just type name like random#1234

steep estuary
hushed galleon
#

no, i dont think discord's api provides that kind of fine grained adjustments

hushed galleon
runic whale
# hushed galleon this question might be more related to <#342318764227821568>, but surely re-exec...

Thanks kindly for the reply. Will give databases a shot!

Essentially the query is stored in a dataframe, which successfully passed on to the discord bot command. Although I am unsure how to tackle the refresh process of sorts. Each time the command is used, I get a random row, but it doesn't change, same random row over and over. I'm not sure how to retrigger the query to run again once the command executes and returns something in a discord channel. Is there a way to ensure the script gets re run after a condition like the command has been used?

Sorry if this is unclear, very new haha.

hushed galleon
#

well it sounds like you want the command to be making the query each time then
e.g. py @bot.command() async def my_command(ctx): async with connection_pool.acquire() as conn: row = await conn.fetchrow( "SELECT something FROM table WHERE id >= MAX(id) * RANDOM() LIMIT 1" ) await ctx.send(f"picked: {row['something']}")

unreal iron
runic whale
hushed galleon
# unreal iron How to do that? sorry if I sound dumb
async def my_command(interaction, user: str):
                                      ^^^^^``` that part is typehinting the `user` parameter with str, so to typehint it with discord.Member you would write: ```py
async def my_command(interaction, user: discord.Member):
                                      ^^^^^^^^^^^^^^^^```
hushed galleon
unreal iron
runic whale
hushed galleon
true robin
#

Traceback (most recent call last):
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "c:\Users\danie\Desktop\Programação\Discord bots\Dlr-Bot 2.22\main.py", line 50, in green_button
await interaction.response.edit_message(embed=embed3, view=View())
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 769, in edit_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
Ignoring exception in view <View timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Votar' emoji=<PartialEmoji animated=False name='✅' id=None> row=None>:
Traceback (most recent call last):
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "c:\Users\danie\Desktop\Programação\Discord bots\Dlr-Bot 2.22\main.py", line 50, in green_button
await interaction.response.edit_message(embed=embed3, view=View())
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 769, in edit_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before

#

help pls

#
@discord.ui.button(label="Votar", style=discord.ButtonStyle.green, emoji="✅", custom_id='persistent_view:green')
    async def green_button(self,interaction:discord.Interaction, button:discord.ui.Button):
        

        # Consultar o banco de dados para obter informações sobre a mensagem e a votação atual
        cursor.execute("SELECT id_user, url, author, content, votos FROM main WHERE message_id = ?", (interaction.message.id,))
        result = cursor.fetchone()
        
        if result is not None:
            id_user, url, author, content, votos = result
        else:
            await interaction.response.defer()
            await interaction.followup.send(content="A mensagem não foi encontrada no banco de dados!", ephemeral=True)
            return

        if id_user is not None and id_user == interaction.user.id:
            # A mensagem já foi votada pelo usuário
            await interaction.response.defer()
            await interaction.followup.send(content="Você já votou nesta foto!", ephemeral=True)
        else:
            # A mensagem ainda não foi votada pelo usuário
            votos += 1 
            sql = ("UPDATE main SET votos = ?, id_user = ? WHERE message_id = ?")
            val = (votos, interaction.user.id, interaction.message.id)
            cursor.execute(sql, val)

        embed3 = discord.Embed(title='📸  Nova Foto Enviada  📸, Votos {}'.format(votos), 
            description=f'Foto de {author}\nJogo: {content}', color=3407616)
        embed3.set_image(url=url)
        
        await interaction.response.edit_message(embed=embed3, view=View())
slate swan
#

interaction.followup.edit use this instead of interaction.response.edit

twilit veldt
#

How I can delete 100 messages per second, in this code??? The messages, should still delete, until there is no more messages, Except the Pinned messages? Can anyone help me?

Code:

async def handle_incorrect_message(message):
global count
count = 0
print("-------------------------------------------")
print("Discord Reset Successful")
with open(data_file, 'r+') as f:
data = json.load(f)
data['last_count'] = count
f.seek(0)
json.dump(data, f)
print("Json Reset Successful")
await message.add_reaction("❌")
await message.channel.send(f"An incorrect number or operation has been written, channel is being reset, please wait!")
overwrites = {message.channel.guild.default_role: discord.PermissionOverwrite(send_messages=False)}
await message.channel.edit(overwrites=overwrites)
print("Reject Send Messages")
await asyncio.sleep(5)
await channel.purge(limit=None, check=lambda message: not message.pinned)
overwrites = {message.channel.guild.default_role: discord.PermissionOverwrite(send_messages=True)}
await message.channel.edit(overwrites=overwrites)
print("Allow Send Messages")

clear elm
#
@bot.tree.command(name="add", description="Adds a user to the ticket.")
async def add(interaction, member:discord.Member):
  if not interaction.channel.name.startswith('ticket-'):
    await interaction.response.send_message('This is not a ticket channel.', ephemeral=True)
    return
    await interaction.channel.set_permission(interaction.member, view_channel=True, send_messages=True, read_messages=True)
    await interaction.response.send_message(f"{interaction.member.mention} has been added from the ticket.", ephemeral=True)``` im trying to make it so if someone uses it, they can choose someone to join the ticket channel everything but adding the permissions work
slate swan
#

ModuleNotFoundError: No module named 'discord_components'

#

help

smoky sinew
smoky sinew
#

!d discord.abc.GuildChannel.set_permissions

unkempt canyonBOT
#

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

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

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

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

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

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

i have code:

            async with aiohttp.ClientSession() as session:
                webhook = discord.Webhook.from_url(webhook_url,
                                                   session=session)
                msg = await webhook.send(embed=embed, wait=True)
                await msg.add_reaction("✅")

but i have an error
AttributeError: PartialWebhookState does not support http methods.

how can i add reaction on this message?

clear elm
# unkempt canyon
@bot.tree.command(name="add", description="Adds a user to the ticket.")
async def add(interaction, member:discord.Member):
  if not interaction.channel.name.startswith('ticket-'):
    await interaction.response.send_message('This is not a ticket channel.', ephemeral=True)
    return

    overwrites = {
            interaction.user: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_messages=True)
    } 
    
    await interaction.channel.set_permissions(interaction.member, view_channel=True, send_messages=True, read_messages=True, overwrites=overwrites)
    await interaction.response.send_message(f"{interaction.member.mention} has been added from the ticket.", ephemeral=True)``` like this?
smoky sinew
#

nvm i think you can pass in dict too

clear elm
#

is it right tho?

smoky sinew
#

why don't you try it

smoky sinew
terse coyote
smoky sinew
#

i'm not sure hold on

terse coyote
twilit veldt
sick birch
#

you don't

smoky sinew
twilit veldt
smoky sinew
twilit veldt
smoky sinew
#

i've already said how to do it

#

if you have a configuration for a counting channel, you can just automatically update it

twilit veldt
smoky sinew
#

mee6 does that?

#

let me try then

twilit veldt
slate swan
#

loooli don't compare your bot to mee6, it's a bot that got verified and unverified lmao

rare echo
thorn nova
#

Noob question sorry guys, is the standard for publishing your bot to create a new instance of the bot project on the server every time the bot is added?

#

Otherwise, for a bot that is deployed across a wide number of servers, how do you go about giving it the ability to monitor and respond to potentially many queries and commands at once? Is multithreading enough?

slate swan
#

discord.py handles that, you don't need to worry about that as long as you're not using blocking drivers

smoky sinew
#

it can handle many tasks at once

thorn nova
#

Would you recommend standard discord.py or pycord more for someone looking to build a relatively simple bot that has a few commands and can respond to messages on certain channels?

smoky sinew
#

but pycord is basically hard forked; it does not keep up with the regular discord.py

rare echo
#

not the server

smoky sinew
#

yes that's what i suggested

thorn nova
smoky sinew
#

where are you getting that information from

urban nebula
#

From my experience but saying that I’ve been using it outdated for so long now and have realised you need to use bot not client

smoky sinew
#

it's the exact same process as adding a message command

urban nebula
#

Not spreading false information, calm it

urban nebula
smoky sinew
#

sorry

thorn nova
#

@smoky sinew Only meant that from what I've seen if you want to incorporate slash commands into discord.py you need to mess with command tree syncing, and so far I haven't needed to do that with pycord. Both are new libraries to me though, so I'm sure I've got some of this stuff wrong.

smoky sinew
#

commands are synced by yourself

#

i usually would recommend making a message command to sync

#

or use jishaku which has that and other helpful tools

thorn nova
#

Sweet, I'll check out jishaku

#

Thanks for the help 👍

smoky sinew
#

np

tropic dirge
#

Getting the error Pylance(reportMissingImports) when trying to import discord.utils any clue how to fix this? I've tried some stuff but Google hasn't been very helpful

naive briar
#

Can you send the full error

grand hazel
#

how do i use another bot to fetch an embed's description and print it using discordpy?

tropic dirge
#
2023-03-03 19:14:26,031 - discord.client - WARNING - PyNaCl is not installed, voice will NOT be supported - __init__ - line 263
[2023-03-03 19:14:26] [WARNING ] discord.ext.commands.bot: Privileged message content intent is missing, commands may not work as expected.
2023-03-03 19:14:26,033 - discord.ext.commands.bot - WARNING - Privileged message content intent is missing, commands may not work as expected. - _async_setup_hook - line 216
[2023-03-03 19:14:26] [INFO    ] discord.client: logging in using static token
2023-03-03 19:14:26,033 - discord.client - INFO - logging in using static token - login - line 571
[2023-03-03 19:14:26] [INFO    ] discord.gateway: Shard ID None has connected to Gateway (Session ID: d4aedab847a346ff7a76ac52768388f6).
2023-03-03 19:14:26,863 - discord.gateway - INFO - Shard ID None has connected to Gateway (Session ID: d4aedab847a346ff7a76ac52768388f6). - received_message - line 561
Bans Bot Online
Unable to process ban (BM Error) for server Artifact Error: 'meta'
smoky sinew
#

for example, on poetry, you would have to do poetry shell and then code .

tropic dirge
smoky sinew
#

nevermind

tropic dirge
#

looking at the documentation though all of the console output i'm getting is normal

#

aside from

Unable to process ban (BM Error) for server Artifact Error: 'meta'
wanton pebble
woeful magnet
#

what is giveaway in discord, can anybody explain me?

smoky sinew
#

is this related to discord bots

woeful magnet
#

giveaway is also related to giveaway bot, isn't it?

smoky sinew
clear elm
#

is there a way to make a https/liverserver in vsc?

smoky sinew
clear elm
#

like this to host it using https

smoky sinew
#

do not host on replit

#

but

#

there is a live server extension on vscode

clear elm
clear elm
smoky sinew
#

look up live server in vscode extensions

smoky sinew
clear elm
#

oh

smoky sinew
#

you can't host your bot on vscode

clear elm
#

oh

#

do u know anything that can host for free?

smoky sinew
#

just self host if you can, you can buy a raspberry pi and if you don't pay electricity it's mostly free

smoky sinew
#

amazon 🤮

sinful thistle
#

Anyone wanna work with me on a discord bot?

echo wasp
#

what is the new way of running on_ready in a cog?

smoky sinew
sinful thistle
#

DM me

echo wasp
smoky sinew
#

it's just a regular event

#
@commands.Cog.listener()
async def on_ready(self):
    ...
echo wasp
#

i tried that but it not doing it

#

as I have in the cog the presence

#

change

#

and the cog is loading

echo wasp
drifting arrow
#

Do I have to restart my entire bot to get new slash commands? or can I simply reload the cog?

smoky sinew
#

make a message command that runs bot.tree.sync

drifting arrow
#

NEATO

drifting arrow
naive briar
#

Doesn't matter

#

It's just a var name

smoky sinew
woeful magnet
#

plz tell me how to add multiple clients discord.py code

naive briar
#

Just do it

woeful magnet
sinful thistle
#

use 2 adding clients commands

woeful magnet
sinful thistle
#
import discord
bot = discord.Client(command_prefix = '!', intents = discord.Intents.all())
client = discord.Client(command_prefix = '', intents = discord.Intents.all())

this should do

naive briar
#

discord.Client constructor does not have command_prefix argument

clear elm
#

is it possible to make a webserver in vscode to host a discord bot?

woeful magnet
naive briar
#

No

smoky sinew
#

vscode is a text editor

woeful magnet
vale wing
clear elm
#

no not replit but u can do it in replit

vale wing
vale wing
clear elm
#

OH

#

i didnt see that

#

😭

smoky sinew
clear elm
#

i cant really self host becasue this laptop is for school as well as personal

vale wing
smoky sinew
#

they start at $10

vale wing
#

On what marketplace they cost 10$

#

In my country they all are like at least 300$

civic fractal
#

for a recent model

vale wing
#

Ah yes happens

smoky sinew
#

look at raspberry pi zero

clear elm
#

is there anything else?

smoky sinew
#

like computers?

vale wing
vale wing
clear elm
vale wing
#

Like I did, but I had those parts already

civic fractal
civic fractal
#

at that point just buy an old laptop

#

or buy a shitty vps for like $5/mo

smoky sinew
#

and it’s not “shitty”

civic fractal
#

i mean

vale wing
#

Personally I have a server built from scrap which is like pentium D 945 + 3 GB RAM and some HDD, and I rent a VPS on aeza.net for 5$/mo

#

The VPS has Ryzen 9 5800 and 2gb ram I think

civic fractal
#

I've got a couple c6g.4xlarge instances on aws

unkempt canyonBOT
#

Hey @woeful magnet!

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

smoky sinew
#

@woeful magnet because bot.run is blocking

woeful magnet
#

I want multiple clients connect to Discord simultaneously using their own user accounts in python but my code doesn't work, only shows "First Client has connected to Discord"
I have attached my code.
https://paste.pythondiscord.com/wefalovomo

civic fractal
#

client.run will not return until the bot has logged out

woeful magnet
civic fractal
#

each bot should be running in its own thread

woeful magnet
civic fractal
#

it is possible that this is as simple as ```py
from threading import Thread

Thread(client1.run).start()
Thread(client2.run).start()
Thread(client3.run).start()```

#

I cant recall if discord.py supports multithreading like this

#

also you may want to join the threads

smoky sinew
woeful magnet
smoky sinew
#

first of all self bots are against tos

#

second of all what is the reason for running 3 bots in the same code

#

i don't even think discord.py has a bot=False method anymore

#

yep it doesn't

civic fractal
woeful magnet
woeful magnet
smoky sinew
#

it's against the rules

civic fractal
#

just use bots

woeful magnet
smoky sinew
#

yes

woeful magnet
smoky sinew
#

even the discord.py official server does not help with it

woeful magnet
smoky sinew
#

so basically modmail

woeful magnet
smoky sinew
#

modmail?

civic fractal
#

Just have your server members dm a bot

#

why do they need to dm you personally

smoky sinew
civic fractal
#

if you're trying to automatically categorize your personal DMs, then that's simply not allowed

smoky sinew
woeful magnet
smoky sinew
#

if they dm the modmail bot yes

woeful magnet
smoky sinew
#

that's not allowed

naive briar
#

Not possible

#

How many times did people tell you this already

woeful magnet
smoky sinew
#

it's open source

#

most python software is

#

under AGPL 3

woeful magnet
smoky sinew
#

please do not ask with help for self bots

woeful magnet
smoky sinew
#

@woeful magnet

woeful magnet
smoky sinew
#

it's against discord tos and this server's rules

civic fractal
woeful magnet
#

what is tos?

smoky sinew
#

Automating normal user accounts (generally called "self-bots") outside of the OAuth2/bot API is forbidden, and can result in an account termination if found.

woeful magnet
#

Great. I got it. I won't do that.

#

thanks

trim parrot
#

guys so

#

i wanted to make a discord bot

#

that informs users of new roblox limited items

#

and when i run the code and send a dm to it (!check)

smoky sinew
#

does roblox allow you to do that 🤔

trim parrot
#

this is what happens

#

please help

smoky sinew
#

how are we supposed to help you without your code

trim parrot
#

wait

#

import discord
import requests

DISCORD_BOT_TOKEN = 'discord token'

client = discord.Client(intents=discord.Intents.default())

@client.event
async def on_ready():
print('Bot is ready.')

@client.event
async def on_message(message):
if message.content.startswith('!check'):

    response = requests.get('https://api.roblox.com/marketplace/limited-items')
    data = response.json()


    for item in data['data']:

        if item['isNew']:

            await message.channel.send(f"A new limited item is available: {item['name']}")

client.run(DISCORD_BOT_TOKEN)

smoky sinew
#

data["data"] does not exist

trim parrot
#

so

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.

smoky sinew
#

also don't use requests with discord.py use aiohttp instead

trim parrot
#

bro just edit my code💀💀

smoky sinew
#

i looked and roblox does not have a /marketplace/limited-items endpoint

#

so that would be your issue

trim parrot
#

hm

#

so the whole thing is wrong

#

my fault lol

unkempt mauve
#

How do I set the bot to only create channels under a category when executing slash cmd

smoky sinew
#

what do you mean?

unkempt mauve
#

where if people execute /open, it will open a ticket channel for them under the tickets category

smoky sinew
#

!d discord.CategoryChannel.create_text_channel

unkempt canyonBOT
#

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

A shortcut method to [`Guild.create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") to create a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") in the category.
unkempt mauve
#

how do I set the category

smoky sinew
#

it already is set

naive briar
#

Did you read what I says

unkempt mauve
#

huh

smoky sinew
#

A shortcut method to Guild.create_text_channel() to create a TextChannel in the category.

unkempt mauve
#

I want it to create channel under a category not that category where the command is executed

smoky sinew
naive briar
#

What? Just get the category?

#

!d discord.Guild.get_channel

unkempt canyonBOT
#

get_channel(channel_id, /)```
Returns a channel with the given ID.

Note

This does *not* search for threads.

Changed in version 2.0: `channel_id` parameter is now positional-only.
unkempt mauve
#

get_category u meant

smoky sinew
#

no

#

a category is a channel

naive briar
smoky sinew
#

that's why it's called CategoryChannel

unkempt mauve
#

thanks the ticket is opened!

smoky sinew
#

ok

static holly
#

all work fine and no error in log in vs code...

#

i dont understand...

grand hazel
#

anyways, does anyone know why when i use my bot to ping user based of their user ids on embeds, it just show bunch of numbers. but in mobile, it shows the bot pinging them, csan anyone help?

static holly
grand hazel
static holly
grand hazel
#

idk tho i regularly use ctx

static holly
glad cradle
#

probably the Bot is taking more than 3 seconds to respond to the interaction

#

there are also cpu bound operations in your code, I don't think they're thread safe, are they?

static holly
#

and now, no error...

static holly
naive briar
#

You're sending the message to the channel but not responding to the interaction

vagrant brook
#

oh i misread sorry

static holly
static holly
low sinew
#

i need help for this

meager chasm
low sinew
#

nevermind

#

all good

vagrant ingot
meager chasm
#

i see

#

that sounds very malicious lol

vagrant ingot
#

Yeah, lol

white citrus
#

Can someone help

quick gust
#

with...?

woven iris
#

lmao

white citrus
# quick gust with...?
Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 370, in _scheduled_task
    await item.callback(interaction)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\user_moderation\view.py", line 156, in callback
    await inter.response.send_message(view=view)
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 866, in send_message
    await adapter.create_interaction_response(
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 184, in request
    raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).```
#

This, i have no idea why

quick gust
#

send your code. Also I have no experience with select menus so wait for somebody else to help you

quick gust
#

one that errored

white citrus
naive briar
white citrus
# naive briar What is `SelectEditWarn`
class SelectEditWarn(nc.ui.Select):
    def __init__(self, target, options):
        super().__init__(placeholder="Choose a case", min_values=1, max_values=1, options=options)
        self.target = target
        self.options = options
    
    async def callback(self, inter: nc.Interaction):
        select_value = self.values[0].split()[1]
        async with aiosqlite.connect("maja.db") as db:
            async with db.cursor() as cursor:
                await cursor.execute('SELECT reason FROM warn_system WHERE user_id = ? AND guild_id = ? AND case_id = ?', (self.target.id, inter.guild.id, select_value))
                reason = await cursor.fetchone()
                formated_reason = ''.join(reason)

                print(formated_reason)
                view = EditWarnModal(self.target.id, select_value, formated_reason)
                await inter.response.send_message(view=view)```
quick gust
#

is it because you're setting max_values?

white citrus
#

No

hushed galleon
#

Modals cant be sent with regular messages, for that you need send_modal

#

!d discord.InteractionResponse.send_modal

unkempt canyonBOT
#

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

Responds to this interaction by sending a modal.
karmic nimbus
#

how to counting owned roles? I use this but the result is increased by 1

counts = len(member.roles)```
vagrant brook
#

just minus 1 ...?

#

theres @everyone role included i suppose

grand hazel
#

how do i make a discord bot ( interaction ) to leave any server if the server it joined doesnt match my guild id

latent anvil
grand hazel
#

but ok

slate swan
glad cradle
#

you can listen for this event

#

!d discord.on_guild_join

unkempt canyonBOT
#

discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") joins a guild.

This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
hushed galleon
glad cradle
#

wow they've already released another micro

hushed galleon
#

looks like it was just to fix a few incorrect typehints

glad cradle
#

udp packets are now long 74 bytes instead of 70

runic whale
#

Working on getting a random row generator to execute in discord, was able to get some help (thanks again thegamecracks), and have been using aiomysql package to try and accomplish this. Switching over to this has now stopped the command from executing (suspecting my my_first_command variables are off), and the data is being returned strangely, it is pulling column headers and no data. Any suggestions would be most appreciated! Thanks kindly in advance!

# Core Discord bot file to product slash command functionality (WIP)

import interactions
import os
from dotenv import load_dotenv
import mysql.connector as cnx
import datetime
import pandas as pd
import sqlalchemy as sa
import pymysql
import sys
import asyncio
import aiomysql

engine = sa.create_engine('mysql://root:root@localhost:3306/dominion_data')

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD_ID = os.getenv('DISCORD_GUILD_ID')

bot = interactions.Client(token=TOKEN)

loop = asyncio.get_event_loop()

@bot.command(
    name="2kplayer",
    description="Work in progress",
    scope=GUILD_ID,
)
async def my_first_command(ctx):
    conn = await aiomysql.connect(
        host='127.0.0.1',
        user='root',
        password='root',       
        db='dominion_data',
        loop = loop
    )
    cur = await conn.cursor()
    await cur.execute('SELECT first_name, last_name, team_name FROM players_2k22 AS t1 JOIN (SELECT player_id as player_id_t2 FROM players_2k22 ORDER BY RAND() LIMIT 1) as t2 ON t1.player_id=t2.player_id_t2 LIMIT 1;')
    print(cur.description)
    await cur.close()
    conn.close()

bot.start();
hushed galleon
hushed galleon
runic whale
hushed galleon
unkempt canyonBOT
#

Hey @brave moth!

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

brave moth
#

damn it discord. why u had to make it txt

summer burrow
#

you can rename files to make them another extension

hushed galleon
#

ah, it appears this was initially fixed in Gorialis/jishaku#196 before it got removed

hushed galleon
#

whatever version of jishaku you have is before january 24

brave moth
shrewd apex
#

they fixed a memory leak pikachu_sip

runic whale
hushed galleon
#

apparently my virtualenv didnt have setuptools

shrewd apex
shrewd apex
hushed galleon
#

wait so jishaku depends on setuptools, but they dont have it listed as a dependecy?

shrewd apex
hushed galleon
#

uhh you werent upgrading the system python's packages right?

shrewd apex
hushed galleon
#

hmm it sounds like a them problem

shrewd apex
#

probably

dull knot
#
from disnake.ext import commands
import disnake, os, dotenv
import aiohttp


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

    @commands.Cog.listener()
    async def on_ready(self):
        print(f"Cog loaded: {self.qualified_name}")

    @commands.command(name="ask")
    async def ChatGPT(self, ctx: commands.Context, *, Prompt: str):
        async with aiohttp.ClientSession() as session:
            payload = {
                "model": "text-davinci-003",
                "prompt": Prompt,
                "temperature": 0.5,
                "max_tokens": 50,
                "presence_penalty": 0,
                "frequence_penalty": 0,
                "best_of": 1,
            }
            headers = {"Authorization": f"Bearer {API_KEY}"}
            async with session.post("https://api.openai.com/v1/completions", json=payload, headers=headers) as resp:
                response = await resp.json()
                ChatGPT_Embed = disnake.Embed(title=f"Chat GPT's Response:",
                                              description=response["choices"][0]["text"])
                await ctx.reply(embed=ChatGPT_Embed)


dotenv.load_dotenv()
API_KEY = os.getenv("ChatGPT")   

def setup(bot):
    bot.add_cog(ChatGPT(bot))        

I got an error:

Ignoring exception in command ask:
Traceback (most recent call last):
  File "C:\Users\alliy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\core.py", line 172, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\alliy\Desktop\Programs\Neko-Nyan\Neko-Nyan\Cogs\ChatGPT.py", line 30, in ChatGPT
    description=response["choices"][0]["text"])
KeyError: 'choices'

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

Traceback (most recent call last):
  File "C:\Users\alliy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\bot_base.py", line 578, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\alliy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\core.py", line 914, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\alliy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\core.py", line 181, in wrapped
    raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'choices'

I'm guessing this happens cuz I'm passing in the API KEY Inappropriately? Could someone help me out? MyBad

#

I know that there's also a KeyError. But I think the only reason I'm getting the KeyError in the first place is because my code can't access the API. MyBad

#

Correct me if I'm wrong

vocal snow
#

you can print the response and find out

median rivet
#

did discord change how embeds work?

#

I keep getting the "Cannot send an empty message" error

#
    embed = discord.Embed(titile="Coinflip", description="My coin landed on a")
    await dm.send(embed=embed)
slate swan
dull knot
slate swan
#

!traceback

unkempt canyonBOT
#
Traceback

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

A full traceback could look like:

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

If the traceback is long, use our pastebin.

dull knot
# dull knot Fixed it.

ChatGPT's AI fixed it for me MyBad Hate the feeling of having a bot fix my mistakes so I'll try understanding it at least Why_Hampton

#

Found the main cause Shuma_MyBad It was a simple typo in the code.

I wrote "frequence_penalty"
When it should've been "frequency_penalty"

#

Well. Thanks guys prayge_king

left dew
#

how do i check if a user has the active developer badge

slate swan
#

!d discord.User.public_flags

unkempt canyonBOT
slate swan
#

!d discord.PublicUserFlags.active_developer

unkempt canyonBOT
left dew
#

oh its actually added mow ty

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1677949887:f> (10 minutes) (reason: attachments rule: sent 9 attachments in 10s).

The <@&831776746206265384> have been alerted for review.

slate swan
#

bros gone

visual yarrow
#

!unmute 874530550487060490

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @slate swan.

visual yarrow
#

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

slate swan
#
Command "stats" is not found

pls fix above error i am getting this error when i used cogs to divide the commands , events etc but i think i am doing something wrong pls fix this

my bot code is

# Libs
import discord
from discord.ext import commands
import json
from pathlib import Path
import logging
import datetime
import os

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

cwd = Path(__file__).parents[0]
cwd = str(cwd)
print(f"{cwd}\n-----")

#Defining a few things
secret_file = json.load(open(cwd+'/bot_config/secrets.json'))
bot = commands.Bot(command_prefix='-', case_insensitive=True, owner_id=271612318947868673, intents=intents)
bot.config_token = secret_file['token']
logging.basicConfig(level=logging.INFO)

bot.blacklisted_users = []
bot.cwd = cwd

bot.version = '5'

#few things to make easier the code
bot.colors = {
  'WHITE': 0xFFFFFF,
  'AQUA': 0x1ABC9C,
  'GREEN': 0x2ECC71,
  'BLUE': 0x3498DB,
  'PURPLE': 0x9B59B6,
  'LUMINOUS_VIVID_PINK': 0xE91E63,
  'GOLD': 0xF1C40F,
  'ORANGE': 0xE67E22,
  'RED': 0xE74C3C,
  'NAVY': 0x34495E,
  'DARK_AQUA': 0x11806A,
  'DARK_GREEN': 0x1F8B4C,
  'DARK_BLUE': 0x206694,
  'DARK_PURPLE': 0x71368A,
  'DARK_VIVID_PINK': 0xAD1457,
  'DARK_GOLD': 0xC27C0E,
  'DARK_ORANGE': 0xA84300,
  'DARK_RED': 0x992D22,
  'DARK_NAVY': 0x2C3E50
}
bot.color_list = [c for c in bot.colors.values()]

@bot.event
async def on_ready():
    # On ready, print some details to standard out
    print(f"-----\nLogged in as: {bot.user.name} : {bot.user.id}\n-----\nMy current prefix is: -\n-----")
    await bot.change_presence(activity=discord.Game(name=f"Hi, my names {bot.user.name}.\nUse - to interact with me!")) # This changes the bots 'activity'

@bot.event
async def on_message(message):
    #Ignore messages sent by yourself
    if message.author.id == bot.user.id:
        return

    #A way to blacklist users from the bot by not processing commands if the author is in the blacklisted_users list
    if message.author.id in bot.blacklisted_users:
        return

    await bot.process_commands(message)

if __name__ == '__main__':
    # When running this file, if it is the 'main' file
    # I.E its not being imported from another python file run this
    for file in os.listdir(cwd+"/cogs"):
        if file.endswith(".py") and not file.startswith("_"):
            bot.load_extension(f"cogs.{file[:-3]}")
    bot.run(bot.config_token)
#

@visual yarrowi bymistake sent mass ss

#

sorry for that

slate swan
#

!d discord.ext.commands.Bot.load_extension

unkempt canyonBOT
#

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

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.

Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.11)").
slate swan
#

you need to await it

slate swan
left dew
#

how do i make it so it displays 2 badges? ive tried this:

if user.public_flags.hypesquad_bravery:
      e.add_field(name=f"**Badges**", value=f"![emoji_3](https://cdn.discordapp.com/emojis/1066677280652398633.webp?size=128 "emoji_3") Hypesquad Bravery", inline=False)
      if user.public_flags.active_developer:
        e.add_field(name=f"**Badges**", value=f"![emoji_6](https://cdn.discordapp.com/emojis/1066678489811517490.webp?size=128 "emoji_6") Active Developer\n![emoji_3](https://cdn.discordapp.com/emojis/1066677280652398633.webp?size=128 "emoji_3") Hypesquad Bravery", inline=False)```
slate swan
#

await bot.load_extension(...)

slate swan
#

yes but await must be inside async function

slate swan
#

any but you prolly want to load extensions on startup

#

so i would put it inside on_ready event

#

or create main function and do it there

#

and call it at the end with asyncio.run

slate swan
#

move the code that loads extensions to on_ready function

#

and add await before bot.load_extension

slate swan
#

those are simple instructions

#

do you know which lines of your code load extensions?

slate swan
slate swan
#

can someone help me with sending a file

#

with just the discord api

unkempt canyonBOT
#

Hey @median rivet!

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

slate swan
#

!d intents

median rivet
#

what

slate swan
#

Using the discord api *

#

i have made like a full commands handler and such i just need a file uploading system now

#

{'code': 50109, 'message': 'The request body contains invalid JSON.'}
Bad Request
Error: 400

hushed galleon
#

that being said, where did you get this data information from? it doesnt match the API reference at all

#

ok well in elite's example the file value is fine but content doesnt seem right

hushed galleon
#

are you using discord.py 2.0? if so, you need to enable the message_content intent

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

you may also share the full command code

median rivet
# slate swan

I used one this time and I got this in my dm
<discord.embeds.Embed object at 0x000001BD66336950>

median rivet
#

not embed=embed

sick birch
#

If you pass in just embed it thinks it's the actual content of the message

median rivet
#
    embed = discord.Embed(titile="Coinflip", description="My coin landed on a")
    await dm.send(embed)
sick birch
#

embed=embed indicates that the embed object should be rendered as an actual embed

median rivet
#

but when I do embed=embed it doesnt work

sick birch
median rivet
slate swan
median rivet
#

same error

slate swan
#

you could try passing empty character into content but still thats not how it should work

median rivet
slate swan
#

without the embed?

median rivet
#

no embed

slate swan
#

try to rename the varriable embed

median rivet
#

okay

#

It just sent me aaaa again

slate swan
#

what dm is?

median rivet
#
    dm = await ctx.author.create_dm()
slate swan
#

try make it like this

#

await ctx.author.send(...)

#

without creating the dm

upbeat otter
slate swan
#

🤦

median rivet
median rivet
slate swan
#

^

median rivet
#

and theres an error now

slate swan
#

new error?

median rivet
#

yeah

slate swan
#

what dm is now?

median rivet
#
    dm = await ctx.author.send(...)
slate swan
#

🤦

#

you were supposed to put that embed=embed into this

median rivet
#

ohh

#

Its not sending me a message now lol

slate swan
#

code?

median rivet
slate swan
#

did you put it after declaring varriable embed

median rivet
#

no...

#

I'm so stupid

slate swan
#

then you know what to do

upbeat otter
#
embed = discord.Embed(...)
try:
    await ctx.author.send(embed=embed)
except discord.Forbidden:
    ...

It's easy as that nothing complicated

median rivet
#

didnt work

#

🫠 I'll just stick with a normal message

slate swan
#

you can try doing pip install -U discord.py

median rivet
#

it workd

#

I updated it

median rivet
slate swan
#

good to hear

#

How can I add a countdown in the embed?

slate swan
uneven hearth
#

how do i mention a command, is it still </[command_name]:0>?

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...
spiral ibex
#

wait it's possible to code a discord bot in python ?

smoky sinew
spiral ibex
#

Oh okk

#

I know it was possible in json

smoky sinew
#

you can't code a discord bot in JSON

spiral ibex
#

WHAT

#

okk I really dont understand ^^''

smoky sinew
#

you are probably thinking of javascript

verbal hawk
#

Hi yall, I want to add a delete button onto my help command, how could I pass a message object? I have to call the class when I send the message.

@bot.tree.command()
async def help(interaction: discord.Interaction):
    
    embed = discord.Embed(title="Help Panel",
                          description="text here",
                          color=0xD2042D)
    embed.set_footer(text="Help was requested by: {}".format(interaction.user.display_name))
    
    class Helpdelete(discord.ui.View):
        def __init__(self, message):
            super().__init__()

        @discord.ui.button(label="🗑️", style=discord.ButtonStyle.red)
        async def menu1(self, button: discord.ui.Button, interaction: discord.Interaction):
            try:
                await message.delete()
            except Exception as e:
                print(e)

    message = None
    message = await interaction.response.send_message(embed=embed, view=Helpdelete(message))

Where/how could I pass a message object to the menu1 function in order to delete it?

#

...or I could make it with reactions ik but this would look wayyyy nicer

smoky sinew
#

interaction.message.delete?

#

why do you have a nested class

verbal hawk
verbal hawk
echo wasp
#

hi, I'm migrating from 1.7.3 to 2.2 but i can't get the task loop to start

smoky sinew
#

not in that way at least

smoky sinew
echo wasp
#

that doesn't work what do i change?

verbal hawk
smoky sinew
#

interaction and button are switched is your issue

#

but also there's no point in putting the class inside the function

verbal hawk
#

I've used interaction.message.delete() but the button is the interaction...?

smoky sinew
#

yes because you switched the order

hushed galleon
# echo wasp

unindent your cog_load function, or alternatively .start() your loop in init directly

verbal hawk
verbal hawk
smoky sinew
#

the order of arguments in your function

verbal hawk
smoky sinew
verbal hawk
#

what can this error mean?

RuntimeWarning: coroutine 'PartialMessage.delete' was never awaited
  interaction.message.delete()
slate swan
#

add await before

smoky sinew
#

that interaction.message.delete wasn't awaited???

verbal hawk
#

it was, I just didn't save it facepalm sorry

slate swan
#

Hi

#

If anyone can help, how can I use modals in py

smoky sinew
unkempt canyonBOT
#

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

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

New in version 2.0.

Examples...
slate swan
karmic nimbus
#

how do i reverse the list? so mods roles can be in first list

    roles = ', '.join([role.mention for role in member.roles if role != ctx.guild.default_role])```
slate swan
#

you can reverse a list using list.reverse() method

karmic nimbus
#
    roles = ', '.join([role.mention for role in member.roles if role != ctx.guild.default_role])
    roles.reverse()

like that?

slate swan
#

roles is not a list

#

its a string already

karmic nimbus
#

hmm

slate swan
#

reverse the list with roles

river plank
#

well my bot runs with the on_ready func but doesn't respond, and im using replit

#

is it cause of a outage ?

#

cause no errors when i run any of the commands

hushed galleon
#

random guess but have you enabled the message_content intent? its typically required for text commands to work correctly

smoky sinew
#

you probably shouldn't show your connection URI

river plank
#

wait

#

shit

#

💀

#

there ya go

smoky sinew
smoky sinew
river plank
#

yea

river plank
smoky sinew
#

read the link

river plank
#

yea

#

tryin it out

pliant gulch
#

Not a good idea persay to put your Mongo DB URL in a repl.it which is most likely public unless you paid for premium

slate swan
#

is there someting like discord bot roadmap?

bright wedge
#

Using basic python and discord.py can do many things.

slate swan
smoky sinew
slate swan
#

xD i got given this tool from a good friend of mine.

smoky sinew
#

py -m pip uninstall discord.py
py -m pip install pycord

slate swan
#

@smoky sinew

smoky sinew
#

nvm it's py-cord

#

not pycord

slate swan
#

@smoky sinew

#

@smoky sinew

smoky sinew
slate swan
#

@smoky sinew

#

is it possible to get all the users who reacted to a message?

smoky sinew
unkempt canyonBOT
slate swan
#

I am trying to create an embed reaction role post with buttons wthin a cog but I am not sure how to approach the interactions now, so when the button is clicked, you either get the role or remove it depending if you already ahve it or not. Just wondering if anyone could advise, heres my code: https://paste.pythondiscord.com/xizifilazi cheers, and sorry for spaghetti code.

slate swan
smoky sinew
#

then check if the user has the role of the button, maybe set the button id to the role id

#

i would create a separate class for the view and button though like this:

#
class ReactionRoleButton(discord.ui.Button):
    def __init__(self, role):
        self.name = role[0]
        self.emoji = role[1]
        self.id = role[2]
        
        super().__init__(
            label = self.name,
            custom_id = self.id
        )
    
    async def callback(self, interaction, button):
        ...

class ReactionRoleView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout = None)
        
        for role in roles:
            self.add_item(ReactionRoleButton(role))

await channel.send(
    view = ReactionRoleView(),
    ...
)
#

something like this, i have no idea if it will actually work @slate swan

#

also make sure your reaction role view is persistent so it works after the bot has restarted

slate swan
#

Ok, thank you very much, I'll see what I can do 🙂 thank you for the advise, etc and your time. 🙂

slate swan
#

message = await ctx.channel.fetch_message(message.id)
reactions = message.reactions
for reaction in reactions:
async for user in reaction.users():
print(user.name)

I am getting all the users who reacted to a message. How can I choose someone randomly?

#

you cannot do that on the same file

smoky sinew
#

@woeful magnet i have asked you numerous times to not ask for help with self bots

woeful magnet
#

Hello @smoky sinew can I ask a question?

#

"/giveaway - Bot Response - for a normal giveaway
/greroll - Bot Response - for a giveaway reroll
/racegiveaway - Bot Response - for a race giveaway or something
/glist - Bot Response - shows all active giveaways
/rgreroll - Bot Response - for a race giveaway reroll
/addxp - Bot Response - points given to a user
/blacklistxp add @user - Bot Response - banished from getting XP
/blacklistxp remove @user - Bot Response - can get XP again
/blacklist list - Bot Response -all users who have been blacklisted
/help - Bot Response - receive a list of commands and utilities
/info - Bot Response - information (you know)
/roleinfo - Bot Response - information about your role
/rolelist - Bot Response - lists all main and sub races

Do I have to develop bots separately to implement those slash commands?

smoky sinew
#

no

woeful magnet
#

So it means I can implement all those slash commands in one bot?

smoky sinew
#

yes

woeful magnet
#

I am sorry to ask about self-bots so far.

woeful magnet
# smoky sinew yes

I wanna develop a bot which has those commands above, is there anything I can refer?

smoky sinew
#

what do you mean?

#

you need help on how to implement them?

slate swan
smoky sinew
#

not how to register a command

slate swan
#

Fair enough, 🙂

woeful magnet
woeful magnet
#

I have installed server captcha bot in my server, can other users in my server can see it?

woeful magnet
#

category = server.get_channel(CATEGORY_ID)
^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'get_channel'
Who can help me with this error?

slate swan
#

looks like server is None

#

Send the code where you defined server

smoky sinew
#

@woeful magnet

woeful magnet
smoky sinew
#

send your code

woeful magnet
# smoky sinew send your code

Oh I fixed my error. Then other question
import discord
from discord.ext import commands

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

description = 'An example bot to showcase the discord.ext.commands extension module.'

bot = commands.Bot(command_prefix='?', description=description, intents=intents)

@bot.command()
async def repeat(ctx, times:int, content="repeating..."):
"""Repeats a message multiple times."""
for i in range(times):
await ctx.send(content)

bot.run(' ')

In this code, Where do I put my bot token and how to import that token?

smoky sinew
#

at the end inside bot.run??

naive briar
#

If it's private, then just put it in the run meth

woeful magnet
#

TOKEN = os.getenv('TOKEN')
bot.run('TOKEN')
is it possible?

smoky sinew
#

no

#

you are using the string value of "TOKEN" not the variable

#

!e ```py
test = "hi"
print("test")
print(test)

unkempt canyonBOT
#

@smoky sinew :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | test
002 | hi
woeful magnet
#

I see
TOKEN = os.getenv('TOKEN')
bot.run(TOKEN)
right?

smoky sinew
#

sure

#

try it

slate swan
#
    from discord_components import nextcordComponents, Button, ButtonStyle
ModuleNotFoundError: No module named 'discord_components'```
smoky sinew
#

Discord components are cool, but discord.py will support it on version 2.0. It is hard to wait, so we made a third-party library for using components such as buttons or selects!

#

discord.py has had components for a while now that code is pretty outdated

naive briar
#

What

smoky sinew
smoky sinew
#

@molten zodiac this is not the channel for that

unkempt mauve
#
@bot.event
async def on_application_command(ctx: discord.Interaction):
    channel = discord.guild.get_channel(1081779753578672209)
    await channel.send(f"{ctx.user.id} used the {ctx.command.name} command with options {ctx.options}")```

Bot is not sending any message to the channel...
smoky sinew
#

ctx: discord.Interaction

unkempt mauve
#

yes?

#

whats funny

smoky sinew
#

you don't see anything wrong with that

unkempt mauve
#

why isnt its sending the message

smoky sinew
#

your issue is discord.guild.get_channel

unkempt mauve
#

what do I do

smoky sinew
#

you need a guild instance

naive briar
#

Learn OOP

smoky sinew
#

also does that event exist?

smoky sinew
unkempt mauve
#

I should probably put it in every cmd 💀

smoky sinew
#

no you shouldn't

#

just name it correctly

#

this is misleading to yourself and whoever is reading your code

smoky sinew
#

this channel is for help with discord bots

#

we don't code bots for you

fresh sand
#

@smoky sinew yup sorry man got it

slate swan
#

i want to make a discord bot for giveaway who will choose random participants
and give some lucky points to losers so that next time their winning probability is higher
do i need database to store the lucky points?

smoky sinew
#

i've never heard of that though, that's an interesting system

brittle axle
#

like a bigger database

#

if its just a private bot for a server with your friends then you dont' really need one

#

it depends on the amount of people that is going to use the bot

#

but yea a database is usually recommended

sinful thistle
#

Anyone wanna collaborate to develop a bot (It is gonna be really good i guarantee)

sinful thistle
shrewd apex
#

just use the points in ur random bias as weights no other logic required

sinful thistle
#

No the logic was

#

When a winner gets a credit set their lucky points to 0 and increment the points of others by a number say one and when some1s lucky points reach say 10 give em the prize and set their points to 0, and if there are 1+ superlucky people then pick a random one amongst them and when the people who get their prize after getting selected randomly even after being super lucky, will get n lucky points for patience.

n will be the number of turns they waited after being super lucky

shrewd apex
#

!d random.sample too much complication

unkempt canyonBOT
#

random.sample(population, k, *, counts=None)```
Return a *k* length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).

Members of the population need not be [hashable](https://docs.python.org/3/glossary.html#term-hashable) or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.
shrewd apex
#

use weights

#

it even takes into account multiple winners

sinful thistle
#

Will he allow multiple winners?

slate swan
sinful thistle
#

ok then his solution will do

slate swan
#
    await interaction.response.send_message("Hiii", ephemeral=True)
          ^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Button' object has no attribute 'response'```
#

i am getting this error

#

code?

tacit storm
#

not sure where to go with this but could anyone know whats happening? when i try running a discord bot using a custom made library with docker, it says this, but when i run the bot without docker (using like a normal cmd), it works perfectly fine

#

they're on the same commit both locally and on the docker container

slate swan
slate swan
slate swan
slate swan
radiant bough
#

Which colour matches with discord embed?
Except for discord.Colour.dark_theme()

slate swan
vale wing
slate swan
quaint scaffold
unkempt canyonBOT
#

Hey @dense jackal!

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

smoky sinew
buoyant quartz
#

help me please:
I have been trying to move the emojis for a bot in a seperate server but everytime i do this certain command in this certain server it bugs out and never displays the actual emoji... In other servers the emojis are perfectly fine and in other commands it works fine... whats happening?

buoyant quartz
#

yeah ive changed everything

#

as i said, in other servers when i use this exact command, it seems to work just fine

#

the bot has all the permissions it needs like external server

dense jackal
#

Alright so basically I was coding a modmail bot with discord py and the script got really messy. On top of me not really good at coding, I don't understand alot of stuff in the script. We also tried to add a close command that closes the thread when sent. that command will do so the messages sent in the threads after command is ran wont be sent in the user's dms. Feel free to dm me. I need hard assistance lol.

https://paste.pythondiscord.com/gugefakoki

#

I just need someone to help me make order in that and possibly explain to me how to code that close, open feature

karmic nimbus
#

so i wanted to display user key permission, but i just want to display the important perms like 'manage' or 'ban' how?

like dyno bot whois

buoyant quartz
river plank
#

how do i use a hyperlink in a embed title

naive briar
#

Normally

vale wing
buoyant quartz
vale wing
#

But iirc it had to do something with external emojis permission

buoyant quartz
vale wing
#

Not sure how certain emojis are displayed but others are not

buoyant quartz
vale wing
#

Actually how do you use emojis in text?

buoyant quartz
#

its just \ dice_1

#

then you get a code

vale wing
#

Yeah that's correct way

buoyant quartz
#

thats what i have and i know it cant be my code because in a different server it worked

dull terrace
#

is there any way to find out a buttons custom_id from a bot users perspective

#

is it somewhere in the html or anything

vale wing
dull terrace
#

I only know very basics of web dev so idk

#

I assume theres no way to get at that info client side?

naive briar
#

No

vale wing
naive briar
#

Just use text commands if you don't want people to know

vale wing
#

Respond to interaction ephemerally and use inter.channel.send

dull terrace
#

7739monkathink okay

shrewd fjord
#

Or followup

vale wing
#

@dull terrace actually try reading component custom ID of message of one bot with another bot

dull terrace
#

just printed off message.components after fetching another bots message and got all of the info

slate swan
#

hey, i made a script thatt takes in a list of usernames that a scraped from a server and i want to add all them from the list, ive made the request but i just seem to be getting the status code 400

bright wedge
#

You wanna store users id from a guild?

slate swan
#

I thought I could using this end point and pass the user and the # in the json but i just get the 400 status code

naive briar
#

Are you self-botting

slate swan
#

no

bright wedge
#

I replied to a different user and you are replying to me, I got confused. 😄

slate swan
#

Oh I’m so sorry I didn’t realise so made that post on my alt

#

That is my acc hahaha

bright wedge
#

You just can store the ids

#

In easier way

naive briar
#

That's a self-bot library

slate swan
#

Oh…

#

😭😭😭😭😭😭

#

Errrrr I didn’t know that 😭😭

#

Oops

bright wedge
#

Well that's why called discum , dis-scum , discord scum.

slate swan
#

LOOOL my bad I honestly didn’t do to much research into it I just didn’t want to re add all the people I know again

#

Guess I won’t use that again

bright wedge
#

Well you can but we can't help.

slate swan
#

I only wanna add my friends…. And thought I’d try make something for fun

#

Don’t wanna break tos and get banned

#

:/

bright wedge
#

Find other way to make fun 😄

slate swan
#

Technically I already have the ids so I can carry on making something to add everyone no ?

bright wedge
#

Can't help

slate swan
#

;(

#

Thank you anyways

dull terrace
#

!e

import random
bob = ("tuple", "random", "test")
print(random.choice(bob))
unkempt canyonBOT
#

@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.

test
gusty canopy
#

!e

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

    @discord.ui.button(label="Create a ticket", style=discord.ButtonStyle.blurple, custom_id="ticket_button")
    async def ticket(self, button: discord.ui.Button, interaction: discord.Interaction):
        ticket = discord.utils.get(interaction.guild.text_channels, name=f"ticket-for-{interaction.user.name}-{interaction.user.discriminator}")
        print(ticket)
        if ticket is not None:
            await interaction.response.send_message("Ty už máš otevřený ticket!", ephemeral=True)
        else:
            overwrites = {
                interaction.guild.default_role: discord.PermissionOverwrite(view_channel=False),
                interaction.user: discord.PermissionOverwrite(view_channel=True, send_messages=True, attach_files=True, embed_links=True),
                interaction.guild.me: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_message_history=True)
            }
            channel = await interaction.guild.create_text_channel(name=f"ticket-for-{interaction.user.name}-{interaction.user.discriminator}", overwrites=overwrites, reason=f"ticket for {interaction.user}")
            await channel.send(f"{interaction.user.mention} created a ticket!")
            await interaction.response.send_message("cc", ephemeral=True)

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

@client.command(name="ticket", description="Launches the ticketing system")
async def ticketing(interaction: discord.Interaction):
    embed = discord.Embed(title="Pokuď potřebuješ pomoc, klikni na tlačítko!", color=discord.Colour.blue())
    await interaction.channel.send(embed=embed, view=ticket_launcher())```
#

Uhh

bright wedge
naive briar
#

#bot-commands

#

🫠