#discord-bots

1 messages · Page 266 of 1

sick birch
#

What's the slash command argument type?

lethal drift
#

Not the best package

lethal drift
#

More efficient than checking strings if it was already built into the library

slate swan
#

actually its not such a good example since in this case the libraries are almost the same

lethal drift
slate swan
#

ah for a slash command

lethal drift
#

yup

slate swan
#

didnt read carefuly

lethal drift
#

It's okay!

slate swan
#

okay then

dense barn
#

discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'char' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

My hybrid command does this when used using slash, but command runs fine if I use prefix.

slate swan
#

does your comand take more than 3 seconds to execute

dense barn
#

Just found that out, I need to defer the response first.

#

But I'm using a ViewMenu object from here: https://github.com/Defxult/reactionmenu and there's no implementation of the defer() sort.

#

I wonder if it's okay to mention him here...

#

@silver wolf Hi

#

Anyway, I'll open an issue.

fiery trout
#

In the following code, my output sometimes misses values by only outputing the first guild from my sqlite database. I was able to fix this by removing the following:
@app_commands.guilds(discord.Object(1104720378070315018))
This line makes it so that the command is only synced to a private guild. This fix doesn't make any sense logically, but it just works somehow and the output displays all the guilds from the database.

After removing that line of code, I added code blocks to the output to make it look cleaner, and everything worked as expected.

Then I decided to see what happens if I add back the removed app.command. Now, I get all the guilds, but the code block is only applied sometimes. it's random, screenshot below.

Anyone know what the issue might be with my code? Thank you!

def is_owner(interaction: discord.Interaction):
    if interaction.user.id == Legend:
        return True
    return False

@bot.tree.command(name='sql-guild_leaderboard', description='leaderboard')
@app_commands.check(is_owner)
@app_commands.guilds(discord.Object(1104720378070315018))
async def sql_guild_leaderboard(interaction: discord.Interaction):
    if not interaction.guild:
        return
    conn = sqlite3.connect('LP.db')
    cursor = conn.cursor()
    cursor.execute('''
        SELECT guild_id, COUNT(*) AS click_count
        FROM button_clicks
        GROUP BY guild_id
        ORDER BY click_count DESC
    ''')
    rows = cursor.fetchall()
    if not rows:
        await interaction.response.send_message("No guilds found.")
        return
    output = "Server Leaderboard:\n"
    for row in rows:
        guild_id, click_count = row
        guild = bot.get_guild(int(guild_id))
        guild_name = guild.name if guild else f'Unknown Guild ({guild_id})'
        output += f"{guild_name}: {click_count}\n"
    cursor.close()
    conn.close()
    await interaction.response.send_message(f"```{output}```")
#

last line of code is supposed to look like this, don't know how to format it correctly for discord

frigid estuary
#

What have I done

#

Can someone pls help me?

#

Ive never used replit before

unkempt canyonBOT
#
Using .env files in Python

.env (dotenv) files are a type of file commonly used for storing application secrets and variables, for example API tokens and URLs, although they may also be used for storing other configurable values. While they are commonly used for storing secrets, at a high level their purpose is to load environment variables into a program.

Dotenv files are especially suited for storing secrets as they are a key-value store in a file, which can be easily loaded in most programming languages and ignored by version control systems like Git with a single entry in a .gitignore file.

In python you can use dotenv files with the python-dotenv module from PyPI, which can be installed with pip install python-dotenv. To use dotenv files you'll first need a file called .env, with content such as the following:

TOKEN=a00418c85bff087b49f23923efe40aa5

Next, in your main Python file, you need to load the environment variables from the dotenv file you just created:

from dotenv import load_dotenv()

load_dotenv(".env")

The variables from the file have now been loaded into your programs environment, and you can access them using os.getenv() anywhere in your program, like this:

from os import getenv

my_token = getenv("TOKEN")

For further reading about tokens and secrets, please read this explanation.

slate swan
frigid estuary
#

uhm

frigid estuary
frigid estuary
slate swan
#

the token

frigid estuary
#

but thge token is the secret

#

so how do I ref the secret

slate swan
#

you already did

frigid estuary
#

My brain is not braining

slate swan
#

you know what varriables are?

frigid estuary
#

Yes

slate swan
#

does look like

frigid estuary
#

but idr how to ref them

slate swan
#

my_secret holds the token and you need to get it to client.run

frigid estuary
#

so client.run(my_secret)

hazy spear
#

👀

slate swan
#

try and see

frigid estuary
hazy spear
#

why do u use the " os.environ " thingy

frigid estuary
#

the client is walking not running 😮

hazy spear
#

why dont just put the token inside of client.run

frigid estuary
hazy spear
#

from what bro

frigid estuary
#

cause replit is public

hazy spear
#

oh ok lmao

slate swan
frigid estuary
#

Traceback (most recent call last):
File "/home/runner/Echo-AI/venv/lib/python3.10/site-packages/discord/http.py", line 803, in static_login
data = await self.request(Route('GET', '/users/@me'))
File "/home/runner/Echo-AI/venv/lib/python3.10/site-packages/discord/http.py", line 745, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized

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

Traceback (most recent call last):
File "main.py", line 20, in <module>
client.run(my_secret)
File "/home/runner/Echo-AI/venv/lib/python3.10/site-packages/discord/client.py", line 860, in run
asyncio.run(runner())
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
return future.result()
File "/home/runner/Echo-AI/venv/lib/python3.10/site-packages/discord/client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "/home/runner/Echo-AI/venv/lib/python3.10/site-packages/discord/client.py", line 777, in start
await self.login(token)
File "/home/runner/Echo-AI/venv/lib/python3.10/site-packages/discord/client.py", line 612, in login
data = await self.http.static_login(token)
File "/home/runner/Echo-AI/venv/lib/python3.10/site-packages/discord/http.py", line 807, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.

slate swan
#

did you save your token under TOKEN in secrets?

frigid estuary
#

yes

slate swan
#

so the string that is under that is not a token

#

it either expired or its not a token at all

frigid estuary
#

it is the token

slate swan
#

generate a new one

frigid estuary
#

tokens expire?

hazy spear
#

discord.errors.LoginFailure: Improper token has been passed.

slate swan
#

if you generate a new one old one does

frigid estuary
#

that is the new one

#

I think

slate swan
#

from where did you get the token

shrewd apex
#

u sure u added token and not something like client id?

hazy spear
#

^

shrewd apex
slate swan
#

token is stored here

hazy spear
#

yh just reset and try the new one

#

paste the new one into the secret

frigid estuary
slate swan
#

wrong mention

shrewd apex
slate swan
frigid estuary
shrewd apex
#

if neither of those with reset it

slate swan
#

so it works ..

shrewd apex
#

nice

frigid estuary
#

thnx 😮

hazy spear
#

👍

frigid estuary
slate swan
#

As it says you did not install module easy_pil
Also its not related to channel topic

frigid estuary
#

but why didnt it install....

slate swan
#

Everything can be for discord so does that mean you can Ask everything here

#

The issue itself is not related to discord bots

frigid estuary
#

Im confused now

#

How is it not related to discord bots if its used for images in the discord bots

slate swan
#

Let me get it more Simple for you

#

The error that you are getting does not happen cause of discord bots libraries

frigid estuary
#

ah

modest crag
#

Hey anyone

#

I'm currently working on a discord bot and its connect to a server, running, with perms

#

but is for some reason not picking up the commands

#

it is able to send messages and has admin perms

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.

modest crag
thin raft
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

modest crag
#

it says it is unused

thin raft
#

why are you doing this

modest crag
thin raft
#

im confused

#

why do you need that

vocal laurel
#

U just put the process commands in and that’s it

modest crag
#

So just remove ctx entirely?

ornate sapphire
#

anyone know how to add chat GPT to a discord bot

rugged shadow
#

you'll have to use the OpenAI API

#

but first you will have to get an API key which i think you have to pay for

slate swan
#

!bot

unkempt canyonBOT
#
Command Help

!bot
Bot informational commands.

slate swan
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

sharp whale
#

Hi, i wanted to ask something, can we ping an actual server with the bot?

sharp whale
sick birch
sharp whale
sick birch
#

Ping what server?

sharp whale
#

any server

sick birch
#

You need to be very specific about what you mean here

sharp whale
#

hmm

#

let me think how do i explain it lol, my english is bad

sick birch
#

You can get the gateway latency but not entirely sure if that's what you're looking for

sick birch
#

!d discord.Client.latency

unkempt canyonBOT
#

property latency```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.

This could be referred to as the Discord WebSocket protocol latency.
sick birch
#

Ensure that the latency between heartbeats and acknowledgements is the type of latency you want to measure

sharp whale
#

is it possible?

sick birch
#

A discord server? Or a server in the context of a host machine?

sick birch
#

Is it a web server?

sharp whale
#

no

sick birch
#

What does it do?

sharp whale
#

host servers like, discord bots, minecraft servers etc

sick birch
#

You can probably set up a simple health check endpoint on a web server there
From your Discord bot you'd measure the time between a request and a response

sharp whale
#

how

sick birch
sharp whale
#

hmm

honest falcon
#

Hey, i coded a discord chatbot using chatterbot module (using yml dataset). It can run normally but when i tried to chat it only reply with the first sentence of the dataset like 'hello' and 'hi'

#

my code

#
import discord
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
from  chatterbot.trainers import ListTrainer
from chatterbot.response_selection import get_random_response

bot = ChatBot(name='bot', read_only=True,
                     response_selection_method=get_random_response,
                     logic_adapters=[
                         {
                             'import_path': 'chatterbot.logic.SpecificResponseAdapter',
                             'input_text': 'empty',
                             'output_text': ''
                         },
                         {
                             'import_path': 'chatterbot.logic.BestMatch',
                             'default_response': 'i honestly have no idea how to respond to that',
                             'maximum_similarity_threshold': 0.7
                         },
                         {
                             'import_path': 'chatterbot.logic.MathematicalEvaluation'
                         }

                     ], preprocessors=[
                             'chatterbot.preprocessors.clean_whitespace',

                             'chatterbot.preprocessors.unescape_html',

                             'chatterbot.preprocessors.convert_to_ascii'
                     ]
                     )
trainer = ChatterBotCorpusTrainer(bot)
trainer.train("data.yaml")

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

@client.event
async def on_ready():
    print(f'Connected')

@client.event
async def on_message(message):

    if message.author == client.user:
        return

    response = bot.get_response(message.content)
    print(f'{message.channel}, {message.author.name}: {message.content} response: {response}')
    await message.channel.send(response)

client.run("token")
#

how can i fix this?

vocal snow
#

you haven't enabled message content intents

#

so you're passing an empty string to get_response

honest falcon
#

Python 3.11

vocal snow
#

run python -m pip show discord.py and double check

#

(python could be py or python3 depending on your system)

honest falcon
vocal snow
#

and you're running your code with the python command, right?

honest falcon
vocal snow
#

ok, so that would mean your pycharm venv has some other version of discord.py

#

you would need to check in the Packages tab or something

sharp whale
#

how do i check if the user has a specific permission in a slash command?

#

like in a normal command, i use @commands.has_permissions but this isnt working for the slash command

sharp whale
#

like @commands.has_permission()

turbid condor
#

Check the link

#

It has what u are looking for

hasty coral
#

Error: An error occurred: 'NoneType' object has no attribute 'role'

Idea: If the user has the Premium role in the support server, the lockdown command runs.

@commands.has_permissions(manage_channels=True)
async def lockdown(ctx, channel: discord.TextChannel):
    OTHER_SERVER_ID = '884813207888347228'
    TARGET_ROLE_ID = '1126808097894182954'
    try:
        guild = bot.get_guild(OTHER_SERVER_ID)
        role = discord.utils.get(guild.role, id=TARGET_ROLE_ID)
        member = guild.get_member(ctx.author.id)

        if role in member.roles:
            await channel.set_permissions(ctx.guild.default_role, send_messages=False)
            await ctx.send(f'{channel.mention} has been locked down.')
            
            mod_log_channel = bot.get_channel(mod_log_channel_id)
            await mod_log_channel.send(f'{channel.mention} has been locked down.')
        else:
            await ctx.send("You cannot use this command as you are not a Premium User.")

    except Exception as e:
        await ctx.send(f"An error occurred: {e}")```
naive briar
unkempt canyonBOT
#

get_guild(id, /)```
Returns a guild with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
naive briar
#

And there's no role attribute in the discord.Guild object, only roles

hasty coral
naive briar
#

Just change it to int

hasty coral
#

got it

hasty coral
# naive briar Just change it to int

Something like this?

@commands.has_permissions(manage_channels=True)
async def lockdown(ctx, channel: discord.TextChannel):
    OTHER_SERVER_ID = int('884813207888347228')
    TARGET_ROLE_ID = '1126808097894182954'
    try:
        guild = bot.get_guild(OTHER_SERVER_ID)
        role = discord.utils.get(guild.roles, id=TARGET_ROLE_ID)
        member = guild.get_member(ctx.author.id)

        if role in member.roles:
            await channel.set_permissions(ctx.guild.default_role, send_messages=False)
            await ctx.send(f'{channel.mention} has been locked down.')
            
            mod_log_channel = bot.get_channel(mod_log_channel_id)
            await mod_log_channel.send(f'{channel.mention} has been locked down.')
        else:
            await ctx.send("You cannot use this command as you are not a Premium User.")

    except Exception as e:
        await ctx.send(f"An error occurred: {e}")```
sharp whale
#
@bot.tree.command(name="ban", description="Bans a user")
@discord.app_commands.checks.has_permissions(ban_members =True)
async def ban(interaction, member:discord.Member, reason:str):
    authoruser = interaction.user
    yesbutton = ui.Button(label="Yes", style=discord.ButtonStyle.green, custom_id= "yesbutton")
    BanView = ui.View()
    BanView.add_item(yesbutton)
    await interaction.response.send_message(f"**Are you sure you want to ban {member.mention}?**", view=BanView)
    async def yesbutton_callback(interaction):
        if interaction.user is not authoruser:
            await interaction.response.send_message("**You cannot use this interaction!**", ephemeral=True)
        else:
            await member.ban(reason=reason)
            await interaction.response.send_message(f"✅**Successfully banned {member.display_name}#{member.discriminator}**")
            banembed = discord.Embed(title="Member Banned", description=f"{member.display_name}#{member.discriminator}", color=discord.Color.red())
            banembed.add_field(name="Reason", value=reason)
            banembed.set_author(name=interaction.user.name, icon_url=interaction.user.avatar.url)
            await send_logs_channel.send(embed=banembed)
    yesbutton.callback = yesbutton_callback
    
@ban.error
async def on_ban_error(interaction: discord.Interaction, error: discord.app_commands.AppCommandError):
    if isinstance(error, discord.app_commands.MissingPermissions):
        await interaction.response.send_message("You don't have permissions to use this command!", ephemeral=True)```
#

even when the user who clicked the button is the user who executed the command, the bot says ```Are you sure you want to ban {member.mention}?

#

@naive briarhelp pls

hasty coral
#

The command runs, it looks for the role, but even if i have the role the bot says this:
You cannot use this command as you are not a Premium User.
So it either isn't searching for the role correctly or changing it to an int didn't help

sharp whale
#

i think this will work

#

instead of checking it by the if statement

naive briar
hasty coral
slate swan
naive briar
sharp whale
#

okay

naive briar
#

!d is

unkempt canyonBOT
#
is

6.10.3. Identity comparisons

The operators is and is not test for an object’s identity: x is y is true if and only if x and y are the same object. An Object’s identity is determined using the id() function. x is not y yields the inverse truth value. 4

sharp whale
#

ty

honest falcon
#

Im making a discord chatbot using chatterbot module, but when i try to run it, it keep getting this error:

#

Traceback (most recent call last):
File "C:\Users\Kiyuma\PycharmProjects\pythonProject\discord bot\test.py", line 36, in <module>
intents.messages_content = True
^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Intents' object has no attribute 'messages_content'

#

my code:

slate swan
#

Because you misspelt it

honest falcon
#

oh

slate swan
#

message_content

honest falcon
#

ah

#

im dumb

#

there go my entire noon looking for the fix

hexed forge
#

hey, I could really use some help, I havent coded in discord.py in a super long time. I tried booting up an old utility bot I had and for some reason the commands are not working. Any assistance would be much appreciated.

naive briar
#

!d discord.Intents.message_content

unkempt canyonBOT
#

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

• The message was sent by the client

• The message was sent in direct messages

• The message mentions the client

This applies to the following events...

hexed forge
#
intents = discord.Intents(messages= True)

client = commands.Bot(command_prefix="$", case_insensitive=True, intents= intents)```
#

I did this but nothing changed

#

@naive briar

naive briar
#

Why

hexed forge
#

no clue

naive briar
#

And pretty sure I said message_content, not messages

hexed forge
#

the docs say messages

naive briar
#

What docs

hexed forge
#
 import discord
 intents = discord.Intents(messages=True, guilds=True)
 # If you also want reaction events enable the following:
 # intents.reactions = True

 # Somewhere else:
 # client = discord.Client(intents=intents)
 # or
 # from discord.ext import commands
 # bot = commands.Bot(command_prefix='!', intents=intents)
naive briar
#

Where is that from

hexed forge
#

docs

#

I also tried this

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

client = commands.Bot(command_prefix="$", case_insensitive=True, intents= intents)```
#

but I still got an error line 11, in <module>
intents.message_content = True
AttributeError: 'Intents' object has no attribute 'message_content'

#

@naive briar ?

#

or any1 else that can help?

slate swan
#
import discord
from discord.ext import commands
from functions.json import JSONWrapper

class StaffCog(commands.Cog):
  def __init__(self, bot):
    self.bot = bot
  
  @commands.command(aliases = ["user"])
  async def staff(self, ctx, user: discord.Member):
    await ctx.message.reply("hi")

async def setup(bot):
  await bot.add_cog(StaffCog(bot))```

How do I make this a slash command??
turbid condor
#

Check this out to get an idea on how to make slash_commands

#

It contains almost every thing u need to know

slate swan
#

im using pycord

turbid condor
#

There are examples there too

turbid condor
slate swan
#

pycord uses the discord namespace

turbid condor
#

Well haven't worked with py-cord so don't know what module names it has

slate swan
slate swan
#

delete discord package if you have it installed

turbid condor
slate swan
#

now its not working

#

at all lmao

#

well if you're switching remove async/await from your setup function
also, there's really not much difference in creating slash commands

naive briar
#

I personally don't think that discord.py's app commands stuff is any more complicated than other libraries

slate swan
#

in discord.py you'll have to sync (the application commands using CommandTree.sync) yourself, but that's all

slate swan
# slate swan well if you're switching remove `async/await` from your setup function also, th...
import discord
from discord.ext import commands
from functions.json import JSONWrapper

class StaffCog(commands.Cog):
  def __init__(self, bot):
    self.bot = bot
  
  @commands.command(aliases = ["user"])
  async def staff(self, ctx, user: discord.Member):
    await ctx.message.reply("hi")

async def setup(bot):
  await bot.add_cog(StaffCog(bot))```

to 

```py
import discord
from discord.ext import commands
from functions.json import JSONWrapper

class StaffCog(commands.Cog):
  def __init__(self, bot):
    self.bot = bot
  
  @commands.command(aliases = ["user"])
  def staff(self, ctx, user: discord.Member):
    ctx.message.reply("hi")

def setup(bot):
  bot.add_cog(StaffCog(bot))```
#

?

#

and do I keep the await here await bot.load_extension(f"cogs.{filename[:-3]}")

naive briar
#

You still need to await the ctx.message.reply

slate swan
#

okay

#

but

#

i need async to do await so I add back the async to command?

slate swan
slate swan
#

how do I make it a slash command now?

#
import discord
from discord.ext import commands
from functions.json import JSONWrapper

class StaffCog(commands.Cog):
  def __init__(self, bot):
    self.bot = bot
  
  @commands.command(aliases = ["user"])
  async def staff(self, ctx, user: discord.Member):
    await ctx.message.reply("hi")

def setup(bot):
  bot.add_cog(StaffCog(bot))```
slate swan
hexed forge
#

sys:1: RuntimeWarning: coroutine 'Command.call' was never awaited (can somebody explain what this error means?)

naive briar
#

It means exactly what it said

#

Coroutine 'Command.call' was never awaited

slate swan
#

is there like a intent i need to enable or smt

slate swan
slate swan
slate swan
#

yeah

#

print(bot.cogs) and see if it's there

slate swan
#

you need to pass guild_ids otherwise the command will be registered globaly and it can take up to an hour to pop up

rapid hedge
#

How could I grab timestamps for when a user joins a voice channel, leaves the voice channel, and how long they were in it?

vocal snow
#

!d discord.on_voice_state_update

unkempt canyonBOT
#

discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceState "discord.VoiceState").

The following, but not limited to, examples illustrate when this event is called...
tepid sundial
#

hi
im working on a bot
i use aiohttp and requests
if you can help me
how can i handle the slash commands of my bot?

tepid sundial
quaint obsidian
#

Give me a second.

tepid sundial
#

wait i will search it

#

i send it dm

quaint obsidian
#

It is fine.

#
  1. Import
from discord import app_commands
tepid sundial
quaint obsidian
#
  1. Event and register all slash commands
@bot.event
async def on_ready():
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} commands")
    except Exception as e:
        print(e)
    print(bot.user.name, "is Online")
quaint obsidian
naive briar
#

They just said it

tepid sundial
#

Im making my own lib

naive briar
tepid sundial
#

with aiohttp and requests

quaint obsidian
tepid sundial
naive briar
tepid sundial
quaint obsidian
#

He has more nervers and time.

naive briar
#

You shouldn't mix up sync and async http libraries

tepid sundial
#

aaa why?

quaint obsidian
#

Aren't they both for sync?

naive briar
#

No, aiohttp is for async, it's in the name

tepid sundial
#

ummm im not good at english
Im georgian

naive briar
quaint obsidian
#

So you want to make slash commands only via requests?

#

or aiohttp

tepid sundial
#

requests and aiohttp

#

i cant hanle my command

#

i register it but i cant handle it

quaint obsidian
#

Is it a library like nextcord

#

that you want to remake?

tepid sundial
quaint obsidian
#

You can look nextcord if they did it.

tepid sundial
tepid sundial
quaint obsidian
#

I meant to look in the source code.

tepid sundial
#

but im makin a new library

tepid sundial
quaint obsidian
#

How is it called?

tepid sundial
#

what ?

quaint obsidian
#

Look your dm.

slate swan
#

!d nextcord.SlashOption

unkempt canyonBOT
#
class nextcord.SlashOption(name=None, description=None, required=None, *, name_localizations=None, description_localizations=None, choices=None, choice_localizations=None, ...)```
Provides Discord with information about an option in a command.

When this class is set as the default argument of a parameter in an Application Command, additional information about the parameter is sent to Discord for the user to see.
dense barn
#

how do I defer a hybrid_command(context: Context) properly?

naive briar
unkempt canyonBOT
#

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

Defers the interaction based contexts.

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

If this isn’t an interaction based context then it does nothing.
dense barn
#

I'm getting this error.

naive briar
#

Can't you just send the plain link

slate swan
#
class SearchView(discord.ui.View):
    def __init__(self, bot, timeout: Optional[float] = 90):
        super().__init__(timeout=timeout)

        search_places = getSearchPlaces(3)

        for place in search_places:
            self.add_item(discord.ui.Button(label=place, style=discord.ButtonStyle.blurple, custom_id=place))

    async def callback(self, interaction: discord.Interaction):
        await interaction.response.send_message('hi')``` how does one access the callback of items added with add_item (this is py-cord)
naive briar
#

Not after

dense barn
#

Ohh

naive briar
slate swan
#

thanks

zenith ginkgo
#

my bot asks for input in dms

#

but if i text in the same server its in

#

it takes that as input instead

thin raft
#

huh?

#

How to get answers

Be specific about what you need help with, make sure to include a code example, the error message (if you got one), and an explanation of the problem. Don’t share code or error messages as screenshots, because those helping often need to copy parts of the code or error. If your question still doesn’t get answered, try reading our guide on asking good questions and try again.

slate swan
#

if you dont want the input to be visible to others you can use Modal

#

!d discord.ui.Modal

unkempt canyonBOT
#

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

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

New in version 2.0.

Examples...
zenith ginkgo
#

ty down

slate swan
#

example this

slate swan
#

discord bot stopped working due to new update, 401 - Unauthorized

slate swan
#

i know RIGHT

slate swan
hushed galleon
slate swan
#

the first part of token is user id

hushed galleon
#

your discord bot gets its own token though, separate from your personal account's token which is given by discord after you've authenticated yourself with email/phone+password login (or scanning the QR code)

plucky nest
#

Hi, I have a lockdown command here which works smoothly, however the problem is that when I run it the everyone role is completely reset as an example and only send_messages is changed and the rest is completely reset.

My question - can I write the code so that only the send_messages permission is changed and the other permissions remain the old ones?

@client.command()
@commands.has_permissions(manage_channels=True)
async def lockdown(ctx):
    await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=False)
    await ctx.send("LOCKED")
formal basin
#

so like read channel history

#

=True

plucky nest
formal basin
potent spear
formal basin
#
ctx.channel.set_permissions(ctx.guild.default_role, send_messages=False, view_channel=True)```
#

you have to put that

#

or it wont be True

potent spear
#

seems like that could work

formal basin
#

view channel wouldnt be true

#

if you didnt put it there

plucky nest
plucky nest
#
@client.command()
@commands.has_permissions(manage_channels=True)
async def lockdown(ctx):
    ctx.channel.set_permissions(ctx.guild.default_role, send_messages=False, view_channel=True)
    await ctx.send("LOCKED")
formal basin
#

bro

#

you havent awaited it

plucky nest
#

oh

formal basin
#

need to await ctx.channel.set_permissions

potent spear
#

copy pasting be like

plucky nest
#

Do I have to enter all individual permissions there now?

#

to TRUE OR FALSE?

formal basin
#

the ones you want to ignore just dont put it in there

plucky nest
#

with Overwrite=.. idk, but anyways ty for your help

formal basin
faint glen
#

...

formal basin
faint glen
#

my bad

formal basin
#

this is discord bots

#

not general

faint glen
#

didnt mean to send

formal basin
#

oh ok

plucky nest
#

What would I have to write there if I want that no one can make the @ everyone mention in a channel @formal basin

sick birch
#

You can turn off everyone pings in your server settings, bot isn't necessary

formal basin
slate swan
#
from discord.ext import commands

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

@client.event()
async def on_ready():
    print(f"Bot is ready!")

class InviteButtons(discord.ui.View):
    def __init__(self, inv: str):
        super().__init__()
        self.inv = inv
        self.add_item(discord.ui.Button(label="Claim", url=""))

    @discord.ui.button(label="Press 'Claim'", style=discord.ButtonStyle.blurple)
    async def bobs(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message(url="", ephemeral=True)

@client.command()
async def invite(ctx: commands.Context):
    inv = await ctx.channel.create_invite()
    await ctx.send("Verify", view=InviteButtons(str(inv)))

client.run("")```
thin raft
desert perch
#

I'm trying to get discord.py on pycharm but i get this error, there's nothing saying i should download microsoft visual studio (i've already done this and got the 3 things i needed after watching a few vids and restarted my pc afterwards and still doesn't work)
Here's the full log of the output after trying to run pip install discord: https://pastebin.com/gcj6bbHt

desert perch
#

(Python 3.10 Interpreter, Pip 23.1.2)

desert perch
frigid estuary
#

Im doing this wrong arent I...

sick birch
#

What's the problem?

frigid estuary
sick birch
#

Yeah .startswith takes a tuple

frigid estuary
#

so how can I make it so it can take multiple values?

#

I also want it to ouput multiple values'

#

Is there a way?

novel apexBOT
#

This is not a Modmail thread.

ornate sapphire
#

hello! Im making a discord bot in discord.py. Im trying to make a neat command that varies between different users. They use the command it asks them for the detail and saves their answer to their account. And each person who uses the command it changes

#

anyone have an idea on how I could od it?

frigid estuary
#

No but now i want to do it too 😭

#

@sick birch

#

E

sick birch
frigid estuary
#

yes

sick birch
frigid estuary
#

well, kinda

sick birch
frigid estuary
#

I want it to be able to respond to any of the messages

frigid estuary
#

I am thirsty for knowledge XD

sick birch
#

See my above message for picking a random item from wm_vars

frigid estuary
#

ooh

sick birch
#

You can store that in wm_var like so:

wm_var = random.choice(wm_vars)
#

Then you can simply send that

frigid estuary
#

cool 😄

#

so then how would I make it so it can respond to multiple?

ornate sapphire
#
if message.content.startswith("hey"):
   await message.channel.send("hey")

if message.content.startswith("hi"):
   await message.channel.send("hey")

if message.content.startswith("sup"):
   await message.channel.send("hey")```
frigid estuary
#

Yeah.... I'd end up with a few hundred lines of code then for all the ways of saying hi

ornate sapphire
#

lol true

ornate sapphire
#

try that

frigid estuary
#

😮

naive briar
frigid estuary
#

Then how does it work>

ornate sapphire
ornate sapphire
naive briar
frigid estuary
#

so it can respond to Hi Echo, Hey Echo, Hello Echo, etc etc etc

frigid estuary
ornate sapphire
#
await message.channel.send(f"wr_vars + {author.mention}")```
frigid estuary
#

oh, thnx

ornate sapphire
#

otherwise the response would be
wr_vars {author.mention}

frigid estuary
#

💀

naive briar
ornate sapphire
#

thats exactly what I said and you were like nooooooooo

naive briar
#

Or a less messy way, use regex

frigid estuary
naive briar
ornate sapphire
frigid estuary
frigid estuary
ornate sapphire
naive briar
# frigid estuary how would I do that

!e

words = ("hi", "hello")
message_content = "Hi, I'm zac".lower()

if any(message_content.startswith(word) for word in words):
    print(message_content)


message_content = "I'm zac".lower()

if any(message_content.startswith(word) for word in words):
    print(message_content)
frigid estuary
unkempt canyonBOT
#

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

hi, i'm zac
naive briar
frigid estuary
ornate sapphire
# frigid estuary E

you could always make life easy and do

if message.content.startswith("Echohelp"):
   await message.channel.send("Cant do that yet :(")```
frigid estuary
#

I want to be able to change the prefix when I make a dashboard

ornate sapphire
frigid estuary
#

OwO

ornate sapphire
#
from discord.ext import commands

client = commands.Bot(command_prefix="Echo"

client.command(name="help")
async def on_message(message):
   await message.channel.send("Cant do that yet")```
frigid estuary
#

missing intents

ornate sapphire
#
client = commands.Bot(command_prefix="Echo", intents=intents)```
naive briar
#

I can't get over of how many errors are in that "code"

frigid estuary
naive briar
#

Because that's gonna be way, way easier

frigid estuary
ornate sapphire
#

im tryinggggggggggggggggggggggggggggggggg

frigid estuary
naive briar
#

Not again

frigid estuary
frigid estuary
#

What @naive briar

ornate sapphire
#

I just cant find the codes anywhere

frigid estuary
#

@nova summits

#

@sick birch

vocal snow
#

Why are you using any()?

frigid estuary
#

Cause @naive briar said to

vocal snow
#

Do you understand what any() does?

frigid estuary
#

no

vocal snow
#

!d any

unkempt canyonBOT
#
any

any(iterable)```
Return `True` if any element of the *iterable* is true. If the iterable is empty, return `False`. Equivalent to:

```py
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
vocal snow
#

Notice how it takes an iterable

frigid estuary
#

😮

vocal snow
#

And you're passing the result of message.content.startswith, which is a single boolean

#

What Catlover told you is to call startswith for all possible prefixes, then accumulate those Boolean results in an iterable, and then use any() on said iterable to check if any of those startswith gave you a True

frigid estuary
#

Now Im confused...

vocal snow
#

Ok, let's break the problem down a little

#

How would you check if the message content starts with just the Echo prefix?

frigid estuary
#

if message.content.startswith('Echo')

vocal snow
#

Right

#

Now you also want to check for 'hi Echo', how would you do that?

frigid estuary
#

if message.content.startswith('Hi Echo')

vocal snow
#

How would you write an if statement that allowed Echo OR hi Echo?

frigid estuary
#

uhm... idk if statements yet

vocal snow
#

I see

#

I would recommend learning about those, it's quite an essential part of python

#

It's also helpful to understand the code you write instead of just copy and pasting blindly

frigid estuary
#

k

#

if message.content.startswith('Hi Echo'):
user = message.author
await message.channel.send(f"wr_vars + {author.mention}")
else return
if message.content.startswith('Echo'):
user = message.author
await message.channel.send(f"wr_vars + {author.mention}")
else
break

#

but uhm, thats just 2 variables and theres gonna be like 12 or more

frigid estuary
#

@vocal snow I got it to work

#

Only problem is its choosing the same random choice each time

ornate sapphire
#

lol

frigid estuary
#

fr

vocal snow
# frigid estuary

wr_var is not going to change once you've set it... You need to call random.choice() again if you want a new random value

frigid estuary
#

aw come on....

ornate sapphire
#

hahha JUST when you think you were close

frigid estuary
#

fr

ornate sapphire
#

BOOOM

frigid estuary
#

I FIXED IT

#

just put it in the if statement so its called each time the event runs

#

anddddd

#

the client command dont work

#

reeeeeeeee

#

Can't even tell you that it can't do it 💀

warm roost
#

Can someone dm me to help me with a discord bot I'm making

ornate sapphire
#

kinda same thing but with more people

#

and someone is usually wrong so the other guy fixes it

#

(by someone I mean me)

slate swan
#

**Why iam Getting this problem ** ??
?

frigid estuary
#

How do I make it so it doesnt show my name

warm roost
#

Think*

rugged shadow
warm roost
#

Thing* oh my lord

frigid estuary
rugged shadow
#

you can't, repls will always show your username in the URL

frigid estuary
#

wait, what if I make the website on github and then use git to host it for a custom domain

#

and then link said domain to replit

rugged shadow
#

you can do that i guess

#

or you can just use GitHub pages directly, no need for replit

frigid estuary
#

will it make the discord bot dashboard more complicated though

warm roost
# ornate sapphire or just say it here

PS C:\Users\redss\OneDrive\Desktop\Code Bot> python3 LearCodeBot.py
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
PS C:\Users\redss\OneDrive\Desktop\Code Bot> python3 LearnCodeBot.py
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
PS C:\Users\redss\OneDrive\Desktop\Code Bot>

rugged shadow
frigid estuary
#

ye

rugged shadow
#

yeah it will

frigid estuary
#

e

#

maybe ill just change my replit username

slate swan
#

**Please help me some one what do I need to do for this **

warm roost
frigid estuary
#

pip install python?

warm roost
slate swan
#

@warm roost bro also can u reply me ?

#

:/

frigid estuary
#

hm

slate swan
rugged shadow
rugged shadow
#

you can create a discord.Intents.default() and pass it in to the Client constructor

slate swan
rugged shadow
#

something like

intents = discord.Intents.default()
client = discord.Client(intents=intents)
frigid estuary
#

how do I get my bots discord login link

#

for authorization on the dashboard

#

I wanna finish setting up the links, ive done the first one, but cant find the second

#

CSS and favicon also not working

#

@rugged shadow can you help?

rugged shadow
#

don't know, never made a dashboard

frigid estuary
rugged shadow
#

W burber kig

sick birch
#

it's under "URL Generator"

#

make sure you select at minimum the identify scope

frigid estuary
sick birch
#

That's not a redirect URL pithink

#

That's the bot invite URL

frigid estuary
#

why is it in there Lmao

sick birch
frigid estuary
sick birch
#

you probably added it here by accident

frigid estuary
#

knowing me, probably

sick birch
#

Just hit the little X next to it to remove it as a redirect

sick birch
#

I'm not seeing that option anywhere

#

Ah I see

frigid estuary
#

idk 🤷

sick birch
#

It's under "URL Generator"

frigid estuary
#

why does it still want a redirect

#

I deleted it

sick birch
#

You need a redirect URL for Discord Oauth

frigid estuary
#

how do i find it

sick birch
#

Make one that's pointing to a web server you can access

frigid estuary
#

oh

sick birch
#

Discord users will be redirected to that page with an authorization code which you will have to read

#

Then exchange that for an access token to make requests on their behalf

#

That is, if you're doing the authorization code oauth flow

#

or client credentials grant or whatever they call it these days

frigid estuary
#

IJ want them to be able to login with discord

sick birch
#

yes you will have to go through the entire oauth2 authentication flow to do that

frigid estuary
#

so how do I do that...

sick birch
#

This page goes over it in detail

#

it's not too difficult luckily

#

Keeping all the security stuff well... secure is probably the hard part

frigid estuary
#

k

#

for a redirect I want it to go to

#

But IDEK how to get the link

sick birch
#

Not sure either, if it's on replit

#

It just has to be exposed to the internet and be listening on that endpoint

frigid estuary
#

ye, btw, the link you gave me is relevent info for python too right?

sick birch
#

The Discord API is language agnostic

frigid estuary
#

oh, ok

frigid estuary
#

now its just giving me the invite link

sick birch
frigid estuary
#

My replit website

sick birch
frigid estuary
#

It send me to my discord server

sick birch
#

Ah, that's the bot invite link then

#

Can you show the redirect URLs in your developer portal?

frigid estuary
#

I didn’t put them in the portal

sick birch
#

Then how did you generate the URL?

frigid estuary
#

I followed the steps on the webpage

sick birch
#

What webpage?

frigid estuary
sick birch
#

I mean, the page before that with the button to authorize

frigid estuary
#

The example url, but o replaced client id with my client id and replaced the other data too

sick birch
#

You need to generate the URL from the portal

#

Otherwise it won't match up and you'll get the error

frigid estuary
#

K

zenith basin
#

?

frigid estuary
zenith basin
#

@sick birch ?

sick birch
#

One moment, let me check the docs

#

Ah here it is

frigid estuary
#

Omfg ij realized your name is Bubger Kirg and not Burger King

sick birch
#

!d discord.ForumChannel.threads

unkempt canyonBOT
frigid estuary
#

XD

zenith basin
sick birch
#

objects

frigid estuary
zenith basin
zenith basin
sick birch
#

Where channel is a forum channel

zenith basin
frigid estuary
#

Hm

#

This site must have answers

#

(The answers are generated by AI)

sick birch
#

Pass in the ID

#

Or you can type hint it to have users mention it

zenith basin
#

ok

sick birch
#

It's just like getting a normal channel

zenith basin
#

just making sure

honest falcon
#

Guys i coded a command for a chatbot so user can teach it how to response to things (im using chatterbot module)

#

How it work is the user gonna type a question, then the bot gonna response base on what it learned

#

and if the response is wrong the user gonna type a new response for it

#

and all of that gonna be added into a list so the bot can train

#

but i cant get the question and response to go into the same list

#

my code:

#
import discord
from chatterbot import ChatBot
from  chatterbot.trainers import ListTrainer

bot = ChatBot(name='bot')
trainer = ListTrainer(bot)

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

@client.event
async def on_ready():
    print(f'Connected')

@client.event
async def on_message(message):
    data = [] #list created
    if '!teach' in message.content:
        question = str(message.content) #get the question, example: !teach Hello (the question/user input)
        data.append(str(question.replace('!teach', ''))) #remove the !teach and append the message into the list that created
        response2 = bot.get_response(question.replace('!teach', '')) #the bot gonna try to response to the question to see if it right
        print(data)
        await message.channel.send(response2)
        await message.channel.send('Is this the right answer?')
    elif message.content == ('!y'): #if the response is correct then it exit
        print('ok')
        return
    elif '!n' in message.content: #if the response is not correct then we gonna add the correct response
        answer = str(message.content) #example: !n Hello, how are you (the correct response to the question/user input)
        data.append(str(answer.replace('!n', ''))) #remove the !n and append the message into  list created before
        print(data)
        trainer.train(data) #train from the new list that just created
        await message.channel.send('Learned')

client.run(token)
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.

frigid estuary
#

Why is the page not working? Help 😮

shrewd apex
#

its gonna have only one item and is recreated everytime the event is triggered

shrewd apex
frigid estuary
#

😮

#

I tried adding another render for index2.html but it just gave me errors

#

I need to get the link for the second page so I can use it as the redirect for discord auth

zenith basin
#

@sick birch sorry to ask but how do I get the emoji that was reacted to thread?

frigid estuary
#

@shrewd apex ?

sick birch
sick birch
unkempt canyonBOT
#

property starter_message```
Returns the thread starter message from the cache.

The message might not be cached, valid, or point to an existing message.

Note that the thread starter message ID is the same ID as the thread.
sick birch
#

You can check the reactions of this, it's just a regular message object

zenith basin
sick birch
#

Yeah same way you'd check reaction count for normal messages

frigid estuary
sick birch
#

Quart isn't going to solve that

frigid estuary
#

Then what will?

sick birch
#

Not sure, sorry. I don't use replit as a web server

frigid estuary
#

😮

#

do you know anyone who could help?

zenith basin
sick birch
#

same way you fetch message from normal channels

#

threads are pretty much indistinguishable from regular old text channels so just treat them as such

shrewd apex
honest falcon
shrewd apex
#

so it dosent get overriden everytime the event ocvurs

frigid estuary
honest falcon
shrewd apex
sharp whale
#

how to make that thinking thingy

#

before executing a slash command

slate swan
#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

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

Defers the interaction response.

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

This is only supported with the following interaction types...
grim rock
#

how i can get no. of users in all the guilds ??

slate swan
#

!d discord.ext.commands.Bot.get_all_members

unkempt canyonBOT
#

for ... in get_all_members()```
Returns a generator with every [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") the client can see.

This is equivalent to:

```py
for guild in client.guilds:
    for member in guild.members:
        yield member
left stirrup
#

How are there music bots when using youtube is illegal

naive briar
#

There are many other sources of music than just YouTube

grim rock
honest falcon
#

Im looking for free bot hosting platfrom, im planning to use replit, but wanna know if there any better option
And no i dont have money to pay for vps or etc, and i also dont have credit card, so any option that isnt free or require cc is out of my hand

quick gust
grim rock
honest falcon
grim rock
#

sry bro i cant do anything then...i can tell you if u ever learned js

#

there is app that helps to make discord bot > BOT DESIGNER FOR DISCORD < with a lang BDScript but there is option to write code in javascript...for hosting they use digitalOcean and make you watch ads....140min of hosting /30sec ad...

honest falcon
grim rock
woeful belfry
#

So I am using jupyter notebooks and my jupyter notebook showing this,now idk what to do tbh!

shrewd apex
#

seems like coursera issue with web browser client

woeful belfry
#

So

#

Like , should i report a problem

shrewd apex
#

why are u doing it over net tho can u not download the exercise and do it locally?

woeful belfry
#

Not really,I have to do the excercise online

shrewd apex
#

remove the print it should work

#

the jupyter server is not able to handle the request

#

usually it happens when u try to do i/o operations of huge magnitudes

#

ie input output

woeful belfry
#

Broo

#

It worked ,what are you,god or something,i had been trying since freaking 2 hrs

shrewd apex
#

i guessed 💀

#

it said io error and u were printing stuff

woeful belfry
shrewd apex
shrewd apex
slate swan
shrewd apex
slate swan
#

not even in the server

woeful belfry
#

Thanks mate!

maiden fable
slate swan
maiden fable
quaint obsidian
#

I think discord finally patch nuke bots.

#

they won't work anymore.

#

Yaya.

warm roost
#

Erika

slate swan
shrewd apex
#

also discord cant really patch nuke bots with surity it can just put tighter limits on it since nuke bots are in the end just bots which interact with discord api they cant block their own api can they?

quaint obsidian
# shrewd apex hmm how do u know? <:ducky_sus:987918033504854066>

I have a bot that backups servers like Xenon, but the server is in .json file. The bot is limited when it reach some amount of channel and role editing. Then I restarted the bot, because of bug fix and the bot was still limited. Once I changed the bot token, because I forgot it (the same day probably 2-3 mins after the bug fix.) then the bot was not limited. I tested my theory with other custom bots that I made and it did confirm that discord limits by token. So if a nuke bot get limited it have to change it's own token or to use other bots on the server.

shrewd apex
#

tokens would be a dumb way to limit a bot if u can just change ur token anytime its way better to ban applications at a time

quaint obsidian
#

The application will be banned if reported.

slate swan
#

That's been the case for ages and it doesn't change anything

quaint obsidian
#

Then how I managed to test nuke my own server and now I can't? Maybe I just dump.

shrewd apex
#

skill issue

slate swan
grim rock
#

fr

slate swan
#

you are supposed to use the Bot instance you created

grim rock
#

im nooob

slate swan
#

then why you start discord bot project

grim rock
#

bot

slate swan
#

it needs many advanced pytohn functionality

#

like OOP and async stuff

grim rock
grim rock
slate swan
grim rock
slate swan
#

yes and you do that in a function that is a command

grim rock
#

ohkay so conclusion?

#

i dont need await ctx.send()?

slate swan
grim rock
#

imma get some sleep

shrewd apex
grim rock
shrewd apex
# grim rock thx

also if u want to send all member name u might want to paginate ur response

#

or put it in a file before sending

#

discord has message limits

grim rock
#

im not any python expert im just trying to learn

shrewd apex
#

nope not saying anything particularly mocking except that was funny tbh

grim rock
#

fr

grim rock
slate swan
#

if you need how many members does the guild have why you iterate over it

sick birch
slate swan
#

!d len

unkempt canyonBOT
#
len

len(s)```
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

**CPython implementation detail:** `len` raises [`OverflowError`](https://docs.python.org/3/library/exceptions.html#OverflowError "OverflowError") on lengths larger than [`sys.maxsize`](https://docs.python.org/3/library/sys.html#sys.maxsize "sys.maxsize"), such as [`range(2 ** 100)`](https://docs.python.org/3/library/stdtypes.html#range "range").
sick birch
#

You don't have to iterate over it twice

grim rock
#

iterate means?

slate swan
#

dam

shrewd apex
#

loop over it

sick birch
#

To loop over all items in a list

grim rock
#

ohkay...

sick birch
#

len(s) will give you the length of some iterable s

shrewd apex
#

like say u have a basket of apples u take them out and count them one by one showing it

grim rock
shrewd apex
#

lousy example but thats the gist

sick birch
grim rock
shrewd apex
#

yeah when u could just call len() on the basket :p

grim rock
#

len(client.users)

shrewd apex
#

pro

grim rock
#

💀💀

#

stop bullying me

sick birch
#

there you go

shrewd apex
#

aint bullying ;-;

#

when i saw u send that message i visualized js iterable.length

grim rock
#

okay i

#

lemme make a comman

#
@bot.commands(name='memberCount')
async def memberCount(ctx):
  await ctx.send(len(bot.users))
#

@shrewd apex @sick birch @slate swan hey i did someting

#

have a look at this

#

master piss

slate swan
#

yeah and does it work?

grim rock
#

idk

slate swan
#

so try

shrewd apex
#

hmm will ctx.send cry about it not being a string?

#

been sometime since i did this

slate swan
#

!d discord.ext.commands.Context.send

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

Sends a message to the destination with the content given.

This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.

For interaction based contexts this does one of the following...
grim rock
shrewd apex
#

true

slate swan
#

should be str type so should raise exception

grim rock
#

guys!!!

#

the command is working but....

#

it says 4k + member

#

but bot in only in my server

#

with 48 members

#

how it is possible

#

???

steel loom
#

your getting the users across all of its servers

slate swan
#

47k is way more than 4k

grim rock
slate swan
#

print to console bot.guilds

shrewd apex
#

check how many servers its in

grim rock
#

but how?

shrewd apex
#

len(bot.guilds)

steel loom
#

you want the length of the members attribute of the guild the command is being sent from

grim rock
#

i wiill come tom gus

#

mma getting angry

#

fr

#

bye fr

steel loom
#

what

sick birch
grim rock
#

u im here on phone

#

fr
any sol. for that 47k+ usrs

#

discord gods helped me to grow my bot

slate swan
#

what you want to achieve?

grim rock
slate swan
#

.. with such answers im not able to help you solve your problem

grim rock
#

all the members in all the guilds

slate swan
#

so you already got it

#

its 47k somehow

grim rock
#

but how

#

its illegal

slate swan
#

i dont know its your bot

grim rock
#

i dont know

slate swan
#

what is illegal about bot seeing 47k members

shrewd apex
grim rock
#

no

#

maybe back in 2021

shrewd apex
#

so how long have u been coding?

slate swan
#

i dont know but its clearly his first bot based on his first question xd

grim rock
#

then i left

shrewd apex
#

and u didnt know what an iterable was?

grim rock
#

no

shrewd apex
#

hmm

grim rock
#

i code in bd

shrewd apex
#

sounds sus ducky_sus

grim rock
#

earlier

slate swan
#

you code for 2 years and dont know OOP??

grim rock
#

fr

slate swan
#

dam you code 5min a day or what

shrewd apex
#

whats bd

grim rock
#

over powered

#

ik ez

grim rock
slate swan
#

bd is short for bed

shrewd apex
#

so its like some js spin off?

grim rock
shrewd apex
#

change directory

grim rock
#

see deez nuts

#

*awkward silence

slate swan
#

ok you still need help about discord bots cause this is getting out of this channel topic

shrewd apex
#

someone made a language for discord bots

grim rock
#

yhea from goLang

#

fr

shrewd apex
#

f damn

grim rock
#

then i realised its pulling us from learning actual shit

#

then i started py

#

fr

shrewd apex
#

thats the best thing u said all day 🫡

slate swan
#

learn a bit more of python if you want to dive into discord bots

shrewd apex
#

we dont need any more languages ending with script

grim rock
shrewd apex
#

js is enough ts is way to

shrewd apex
grim rock
#

oh fine

slate swan
grim rock
#

ik def

slate swan
#

def is not what functions have to offer

grim rock
#

async means to sync smth ?

slate swan
#

no

grim rock
#

fr

#

💀💀

slate swan
#

asynchronous

unkempt canyonBOT
#
Concurrency in Python

Python provides the ability to run multiple tasks and coroutines simultaneously with the use of the asyncio library, which is included in the Python standard library.

This works by running these coroutines in an event loop, where the context of the running coroutine switches periodically to allow all other coroutines to run, thus giving the appearance of running at the same time. This is different to using threads or processes in that all code runs in the main process and thread, although it is possible to run coroutines in other threads.

To call an async function we can either await it, or run it in an event loop which we get from asyncio.

To create a coroutine that can be used with asyncio we need to define a function using the async keyword:

async def main():
    await something_awaitable()

Which means we can call await something_awaitable() directly from within the function. If this were a non-async function, it would raise the exception SyntaxError: 'await' outside async function

To run the top level async function from outside the event loop we need to use asyncio.run(), like this:

import asyncio

async def main():
    await something_awaitable()

asyncio.run(main())

Note that in the asyncio.run(), where we appear to be calling main(), this does not execute the code in main. Rather, it creates and returns a new coroutine object (i.e main() is not main()) which is then handled and run by the event loop via asyncio.run().

To learn more about asyncio and its use, see the asyncio documentation.

grim rock
#

intresting...i completely understand

grim rock
#

not what i expected

unkempt canyonBOT
#
Concurrency in Python

Python provides the ability to run multiple tasks and coroutines simultaneously with the use of the asyncio library, which is included in the Python standard library.

This works by running these coroutines in an event loop, where the context of the running coroutine switches periodically to allow all other coroutines to run, thus giving the appearance of running at the same time. This is different to using threads or processes in that all code runs in the main process and thread, although it is possible to run coroutines in other threads.

To call an async function we can either await it, or run it in an event loop which we get from asyncio.

To create a coroutine that can be used with asyncio we need to define a function using the async keyword:

async def main():
    await something_awaitable()

Which means we can call await something_awaitable() directly from within the function. If this were a non-async function, it would raise the exception SyntaxError: 'await' outside async function

To run the top level async function from outside the event loop we need to use asyncio.run(), like this:

import asyncio

async def main():
    await something_awaitable()

asyncio.run(main())

Note that in the asyncio.run(), where we appear to be calling main(), this does not execute the code in main. Rather, it creates and returns a new coroutine object (i.e main() is not main()) which is then handled and run by the event loop via asyncio.run().

To learn more about asyncio and its use, see the asyncio documentation.

grim rock
#

ik to make api requests and formate them so someone can read it

#

i made a bot with perspective api shit that somehow works

kind trellis
slate swan
#

code?

kind trellis
# slate swan code?
redwood = discord.Object(646540220539338773)
...
    @app_commands.command(name="remote-enable", description="Enable remote access for the bot developer")
    @app_commands.guild_only()
    @commands.is_owner()
    @app_commands.guilds(redwood)
    async def remote_enable(self, interaction: discord.Interaction):
        #Command function here
slate swan
#

and where is this code located?

#

in a cog?

kind trellis
#

Yes

slate swan
#

also the commands.is_owner only works on prefixed commands

#

for slash there is other

slate swan
kind trellis
kind trellis
slate swan
#

but the one from commands wont work in slash commands

#

!d discord.app_commands.check

unkempt canyonBOT
#

@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.

These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure") exception is raised and sent to the appropriate error handlers.

These checks can be either a coroutine or not.

Examples

Creating a basic check to see if the command invoker is you...
slate swan
#

is has a nice example

kind trellis
#

Ok, but what about the reason I'm here?

slate swan
#

share the cog code

kind trellis
#

Why do you need to see the entire cog?

slate swan
#

so i can see how it is defined

#

as well as the commands inside it

kind trellis
#
import discord
import datetime
import sys
import traceback

from discord.ext import commands
from discord import app_commands

redwood = discord.Object(646540220539338773)

class RedwoodAutomationITCog(commands.Cog, name="IT Commands"):
    def __init__(self, bot):
        self.bot = bot

    @app_commands.command(name="remote-enable", description="Enable remote access for the bot developer")
    @app_commands.guild_only()
    @commands.is_owner()
    @app_commands.guilds(redwood)
    async def remote_enable(self, interaction: discord.Interaction):
        #Private command function
        pass

    @app_commands.command(name="remote-disable", description="Disable remote access for the bot developer")
    @app_commands.guild_only()
    @commands.is_owner()
    @app_commands.guilds(redwood)
    async def remote_disable(self, interaction: discord.Interaction):
        #Private command function
        pass

    pass

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

@slate swan

slate swan
#

do you sync the command tree?

kind trellis
#

Yes

slate swan
#

when and how

#

also remove the @commands.is_owner() it also might be the reason

kind trellis
#

In a different cog, using ctx.bot.tree.sync()

slate swan
kind trellis
#

Yes, 46 sync, these two don't

slate swan
#

try passing the guild id to the sync

kind trellis
#

Can't

#

Bot is in more than one guild

slate swan
#

so it is supposed to be global?

#

well then it can take up to an hour to register global commands

kind trellis
#

No

#

46 commands are global

#

These 2 aren't

slate swan
#

is there a posibility you sync the commands before cog is loaded?

kind trellis
#

No

slate swan
#

then all i see left is ratelimit for slash commands registered per day

#

what if you try ```py
testing_guild = discord.Object(...)
bot.tree.copy_global_to(guild=testing_guild)

do you see needed commands in this guild?
frigid estuary
#

Im back and I still need help with the token pull request

dusk pumice
#

Umm..
How do I create thread?

#

Anyone here?

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

Creates a thread in this forum.

This thread is a public thread with the initial message given. Currently in order to start a thread in this forum, the user needs [`send_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.send_messages "discord.Permissions.send_messages").

You must send at least one of `content`, `embed`, `embeds`, `file`, `files`, or `view` to create a thread in a forum, since forum channels must have a starter message.
#

await create_thread(*, name, message=None, auto_archive_duration=..., type=None, reason=None, invitable=True, slowmode_delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a thread in this text channel.

To create a public thread, you must have [`create_public_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_public_threads "discord.Permissions.create_public_threads"). For a private thread, [`create_private_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_private_threads "discord.Permissions.create_private_threads") is needed instead.

New in version 2.0.
#

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

Creates a public thread from this message.

You must have [`create_public_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_public_threads "discord.Permissions.create_public_threads") in order to create a public thread from a message.

The channel this message belongs in must be a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel").

New in version 2.0.
dusk pumice
#

Thank you so much!

tough kernel
#

Using slash commands and discord.py. Is there a way to have a drop down list when the user is typing in the slash command?

For example if its a thing like monster that takes a monster name from a list. The slash would be something like /monster (then discord pops up with monster name:) and the user starts typing vampire but as they type that in, it shows all options that contain the letters

thin raft
#

!d discord.app_commands.autocomplete

unkempt canyonBOT
#

@discord.app_commands.autocomplete(**parameters)```
Associates the given parameters with the given autocomplete callback.

Autocomplete is only supported on types that have [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)"), [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.11)"), or [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.11)") values.

[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.

For more information, see the [`Command.autocomplete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete "discord.app_commands.Command.autocomplete") documentation.

Warning

The choices returned from this coroutine are suggestions. The user may ignore them and input their own value...
tough kernel
tough kernel
#

And i dont understand how that can work with slash commands as i have to change the decorator

hushed galleon
#

though personally i prefer implementing autocomplete by subclassing Transformer

tough kernel
#
async def monster_autocomplete(
    interaction: discord.Interaction,
    current: str,
) -> List[app_commands.Choice[str]]:
    monster_names = [monster['name'] for monster in monsters + event_monsters]
    return [
        app_commands.Choice(name=monster_name, value=monster_name)
        for monster_name in monster_names if current.lower() in monster_name.lower()
    ]



@app_commands.command()
@app_commands.autocomplete(monster_name=monster_autocomplete)
async def info(interaction: discord.Interaction, monster_name: str):
    # Search for the monster in both lists
    monster = next((monster for monster in monsters if monster['name'].lower() == monster_name.lower()), None)
    if not monster:
        monster = next((monster for monster in event_monsters if monster['name'].lower() == monster_name.lower()), None)

    if monster:
        # Extract the monster's information
        name = monster['name']
        attack = monster['monster_attack']
        experience = monster['experience']
        image_url = monster['image_url']
        team_size = monster.get('team_size', 'Unknown')

        # Create an embedded message
        embed = discord.Embed(title=name, description=f"Attack: {attack}\nExperience: {experience}\nTeam Size: {team_size}")
        embed.set_image(url=image_url)

        # Send the embedded message
        await interaction.response.send_message(embed=embed)
    else:
        # If the specified monster was not found, send an error message
        await interaction.response.send_message("Monster not found.")