#discord-bots
1 messages · Page 266 of 1
Not the best package
string. I was trying to have it have the dropdown style thing where it says "accept"/"decline"
More efficient than checking strings if it was already built into the library
Discord.py: https://github.com/Rapptz/discord.py/blob/master/examples/views/dropdown.py
Nextcord: https://github.com/nextcord/nextcord/blob/master/examples/views/dropdown.py
here are two libraries check out how they handle the dropdowns and see which one you understand more
actually its not such a good example since in this case the libraries are almost the same
Thank you, but I found it!
this is what I meant tho @app_commands.choices
ah for a slash command
yup
didnt read carefuly
It's okay!
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.
does your comand take more than 3 seconds to execute
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.
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
.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.
you already have the token under my_secret varriable
uhm
I followed the link and google broke
so what do I put in client.run
you already did
you know what varriables are?
Yes
does look like
but idr how to ref them
my_secret holds the token and you need to get it to client.run
so client.run(my_secret)
👀
try and see
why do u use the " os.environ " thingy
the client is walking not running 😮
why dont just put the token inside of client.run
to hide the token
from what bro
cause replit is public
oh ok lmao
full traceback?
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.
did you save your token under TOKEN in secrets?
so the string that is under that is not a token
it either expired or its not a token at all
it is the token
generate a new one
tokens expire?
discord.errors.LoginFailure: Improper token has been passed.
if you generate a new one old one does
from where did you get the token
u sure u added token and not something like client id?
^
gib them tutorial link it has the basics atleast they can use the home page 
token is stored here
A hands-on guide to Discord.py
thats where I got it fromn
wrong mention
then name sure to check for spaces and new lines at end
try doing print(my_secret) and see if it is the token indeed
OwO
if neither of those with reset it
so it works ..
nice
thnx 😮
👍
Re
As it says you did not install module easy_pil
Also its not related to channel topic
but why didnt it install....
its for a Discord Bot
Everything can be for discord so does that mean you can Ask everything here
The issue itself is not related to discord bots
Im confused now
How is it not related to discord bots if its used for images in the discord bots
Let me get it more Simple for you
The error that you are getting does not happen cause of discord bots libraries
ah
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
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.
!intents
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.
it says it is unused
U don’t need the ctx parts
U just put the process commands in and that’s it
So just remove ctx entirely?
anyone know how to add chat GPT to a discord bot
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
!bot
!bot
Bot informational commands.
!intents
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.
Hi, i wanted to ask something, can we ping an actual server with the bot?
What do you mean?
like, can we show a vps latency via bot
Define "VPS latency"
like, there is a server, can we ping it?
Ping what server?
any server
You can get the gateway latency but not entirely sure if that's what you're looking for
yes that
ig
!d discord.Client.latency
property latency```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
Ensure that the latency between heartbeats and acknowledgements is the type of latency you want to measure
but i want to get the latency of a different server
is it possible?
A discord server? Or a server in the context of a host machine?
host machine
Is it a web server?
no
What does it do?
host servers like, discord bots, minecraft servers etc
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
how
Do you know how to use libraries like Flask?
hmm
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?
you haven't enabled message content intents
so you're passing an empty string to get_response
I tried to do it first actually, but it said:
AttributeError: 'Intents' object has no attribute 'message_content'
Im using discord.py 2.3.1
Python 3.11
run python -m pip show discord.py and double check
(python could be py or python3 depending on your system)
I did, i even reinstall the module, it still give me the same error
and you're running your code with the python command, right?
I use the run option when right click on the pycharm tab
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
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
If u are using dpy
is there any decorator for that?
like @commands.has_permission()
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}")```
!d discord.Client.get_guild - the id argument must be passed as an int, not str
get_guild(id, /)```
Returns a guild with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
And there's no role attribute in the discord.Guild object, only roles
so can i change bot.get_guild(other_server_id) to bot.get_guild(int(other_server_id)) or do i have to change the variable to an int?
Just change it to int
got it
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}")```
@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
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
try @commands.has_role(role)
i think this will work
instead of checking it by the if statement
Change your TARGET_ROLE_ID from str to int. And why ID = int('884813207888347228') when you can just remove the quotes and it will be considered an int, like ID = 884813207888347228
i didn't know it worked without the quotations. I have done this and it worked, apologies
can anyone help me
What do you need
Change if interaction.user is not authoruser to if interaction.user != authoruser, so discord.py can do a check on its own
okay
!d is
ty
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:
Because you misspelt it
oh
message_content
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.
Most likely because you do not have the message_content intent, which is added in discord.py 2.0
!d discord.Intents.message_content
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...
Thanks! ill try whatever that is out
intents = discord.Intents(messages= True)
client = commands.Bot(command_prefix="$", case_insensitive=True, intents= intents)```
I did this but nothing changed
@naive briar
Why
no clue
And pretty sure I said message_content, not messages
the docs say messages
What docs
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)
Where is that from
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?
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??
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
Check this out to get an idea on how to make slash_commands
It contains almost every thing u need to know
im using pycord
Then search slash_commands in pycord docs
There are examples there too
From your imports i thought it was dpy
pycord uses the discord namespace
Well haven't worked with py-cord so don't know what module names it has
why is your setup defination async when you're not using discord.py?
update discord.py python -m pip install -U discord.py
delete discord package if you have it installed
You have variable called 'intents' use that instead of Intents like
intents.message_content=True
cause i just switched cause some1 said it was easier to use slash
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
I personally don't think that discord.py's app commands stuff is any more complicated than other libraries
in discord.py you'll have to sync (the application commands using CommandTree.sync) yourself, but that's all
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]}")
You still need to await the ctx.message.reply
no
you need to remove it only from the setup and load_extension(s), nowhere else
okay
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))```
https://guide.pycord.dev/popular-topics/cogs
check the @discord.slash_command decorator
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
sys:1: RuntimeWarning: coroutine 'Command.call' was never awaited (can somebody explain what this error means?)
import discord
from discord.ext import commands
from functions.json import JSONWrapper
class StaffCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@discord.slash_command()
async def worker(self, ctx: discord.ApplicationContext, user: discord.Member):
await ctx.respond("hi")
def setup(bot):
bot.add_cog(StaffCog(bot))```
Tried it the command wont even pop up
is there like a intent i need to enable or smt
- was the bot invited with proper application.commands scope?
- does the bot appear in server integeration settings
- if above satisfies, is the command listed there? if yes, restart your discord
make a new bot turned on the scope, appears in integrations, and restarted no luck
is the cog loaded?
yeah
print(bot.cogs) and see if it's there
you need to pass guild_ids otherwise the command will be registered globaly and it can take up to an hour to pop up
How could I grab timestamps for when a user joins a voice channel, leaves the voice channel, and how long they were in it?
!d discord.on_voice_state_update
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...
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?
You have to use bot tree
whats that?
Give me a second.
im not using discord.py
- 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")
What are you using?
They just said it
Im making my own lib
And that is the most useless try-except block ever
with aiohttp and requests
I know. I just copied it from my old code.
Why both
for fun
He has more nervers and time.
You shouldn't mix up sync and async http libraries
aaa why?
Aren't they both for sync?
No, aiohttp is for async, it's in the name
ummm im not good at english
Im georgian
requests is blocking
no its a library base of discord.py and nextcord
You can look nextcord if they did it.
no im making it from 0 too 100
i know it
Pycord discord.py and nextcord
I meant to look in the source code.
but im makin a new library
i send it to your dm
How is it called?
what ?
Look your dm.
!d nextcord.SlashOption
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.
how do I defer a hybrid_command(context: Context) properly?
!d discord.ext.commands.Context.defer
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.
Can't you just send the plain link
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)
You need to defer before doing anything that will take a long time
Not after
Ohh
Simply create a button variable, assign the callback, then add to the view
thanks
my bot asks for input in dms
but if i text in the same server its in
it takes that as input instead
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.
if you dont want the input to be visible to others you can use Modal
!d discord.ui.Modal
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...
ty down
example 
discord bot stopped working due to new update, 401 - Unauthorized
excellent
i know RIGHT
Update of what
uaernamess
according to docs though 401 is only relevant to your Authorization header, i.e. your bot token is invalid
https://discord.com/developers/docs/topics/opcodes-and-status-codes#http
tokens are associated with usernames+passwords usually
the first part of token is user id
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)
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")
you have to put what perms are which
so like read channel history
=True
I try to understand your comment, unfortunately unsuccessfully 😅
when you dont put a perm in ctx.channel.set_permissions then by default it is that slash thing between the tick and cross
yes, by getting the current permissions for the channel and only changing a specific part
yk what I mean?
ctx.channel.set_permissions(ctx.guild.default_role, send_messages=False, view_channel=True)```
you have to put that
or it wont be True
seems like that could work
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
send your code
@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")
oh
need to await ctx.channel.set_permissions
copy pasting be like
Exactly, now the permissions send_messages and view_channel are taken over and the rest that I now had set to NOT ALLOWED have been reset to default.
Do I have to enter all individual permissions there now?
to TRUE OR FALSE?
well it depends if you want it true or false
the ones you want to ignore just dont put it in there
All right, I thought it would be easier so that you can set it that none of the permissions are overwritten except just the one.
with Overwrite=.. idk, but anyways ty for your help
what the heck
...
go to #python-discussion
my bad
didnt mean to send
oh ok
What would I have to write there if I want that no one can make the @ everyone mention in a channel @formal basin
You can turn off everyone pings in your server settings, bot isn't necessary
Oh. Uhm go on the everyone role then disable @ everyone pings
ok ty bro
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("")```
can you do a pip show discord.py
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I believe it's discord.py
(Python 3.10 Interpreter, Pip 23.1.2)
i still get the same error with this T_T
What's the problem?
Yeah .startswith takes a tuple
so how can I make it so it can take multiple values?
I also want it to ouput multiple values'
Is there a way?
This is not a Modmail thread.
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?
Are you trying to pick a random item from wm_vars?
yes
Yeah, you'd need a database
well, kinda
Use random.choice(wm_vars) after you import random at the top
I want it to be able to respond to any of the messages
I wanna know how to do that too now though
I am thirsty for knowledge XD
See my above message for picking a random item from wm_vars
ooh
You can store that in wm_var like so:
wm_var = random.choice(wm_vars)
Then you can simply send that
you could do an easy way but with more codes
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")```
Yeah.... I'd end up with a few hundred lines of code then for all the ways of saying hi
lol true
list = ["hey", "hi", "wow"]
if message.content.startswith(str(list)):
await message.channel.send("hi")```
try that
😮
That's not how it works at all
I tried
you need an f string on that
What does respond to multiple means
so it can respond to Hi Echo, Hey Echo, Hello Echo, etc etc etc
which one?
await message.channel.send(f"wr_vars + {author.mention}")```
oh, thnx
otherwise the response would be
wr_vars {author.mention}
💀
There are multiple ways to do that, like looping over a list of words (["hi", "hello", ...]) and check if the message content starts with any one of them
brehhh
thats exactly what I said and you were like nooooooooo
Or a less messy way, use regex
whats rregex
how would I do that
I am pretty sure you did not
did too
E
...
that should work
!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)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
hi, i'm zac
Regular expression
how do I use it
you could always make life easy and do
if message.content.startswith("Echohelp"):
await message.channel.send("Cant do that yet :(")```
I want to be able to change the prefix when I make a dashboard
you can do acommand
OwO
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")```
missing intents
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
client = commands.Bot(command_prefix="Echo", intents=intents)```
I can't get over of how many errors are in that "code"
IJ did
client = discord.Client(intents=discord.Intents.all())
intents = discord.Intents().all()
Hmmmm, are you trying to make your bot have many prefixes?
Because that's gonna be way, way easier
no, im trying to make it have a customizable prefix
whattttttttttttttttt
im tryinggggggggggggggggggggggggggggggggg
hm
Not again
I think I understand how it works
I just cant find the codes anywhere
Why are you using any()?
Cause @naive briar said to
Do you understand what any() does?
no
!d 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
Notice how it takes an iterable
😮
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
Now Im confused...
Ok, let's break the problem down a little
How would you check if the message content starts with just the Echo prefix?
if message.content.startswith('Echo')
if message.content.startswith('Hi Echo')
How would you write an if statement that allowed Echo OR hi Echo?
uhm... idk if statements yet
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
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
@vocal snow I got it to work
Only problem is its choosing the same random choice each time
lol
fr
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
aw come on....
hahha JUST when you think you were close
fr
BOOOM
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 💀
Can someone dm me to help me with a discord bot I'm making
or just say it here
kinda same thing but with more people
and someone is usually wrong so the other guy fixes it
(by someone I mean me)
**Why iam Getting this problem ** ??
?
How do I make it so it doesnt show my name
you can't
Thing* oh my lord
wdym
you can't, repls will always show your username in the URL
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
you can do that i guess
or you can just use GitHub pages directly, no need for replit
will it make the discord bot dashboard more complicated though
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>
ohhh you're connecting it to a bot
ye
yeah it will
**Please help me some one what do I need to do for this **
It says python isnt found but I made sure to install it before I started
pip install python?
Yes
hm
can anyone help me
you're missing the intents
you can create a discord.Intents.default() and pass it in to the Client constructor
do i need to install what I need to do for it
don't need to install anything, just create a new Intents object and pass it into Client
something like
intents = discord.Intents.default()
client = discord.Client(intents=intents)
IG I have to doxx myself 🤷
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?
don't know, never made a dashboard
ooh
W burber kig
huh
why is it in there Lmao
you probably added it here by accident
knowing me, probably
Just hit the little X next to it to remove it as a redirect
How are you seeing that? 
I'm not seeing that option anywhere
Ah I see
idk 🤷
You're in the wrong tab
It's under "URL Generator"
You need a redirect URL for Discord Oauth
how do i find it
Make one that's pointing to a web server you can access
oh
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
IJ want them to be able to login with discord
yes you will have to go through the entire oauth2 authentication flow to do that
so how do I do that...
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
Not sure either, if it's on replit
It just has to be exposed to the internet and be listening on that endpoint
ye, btw, the link you gave me is relevent info for python too right?
The Discord API is language agnostic
oh, ok
how do I find state
ffs
now its just giving me the invite link
What did you set as the Oauth2 redirect uri?
My replit website
What happens if you enter in the 2fa code?
It send me to my discord server
Ah, that's the bot invite link then
Can you show the redirect URLs in your developer portal?
I didn’t put them in the portal
Then how did you generate the URL?
I followed the steps on the webpage
What webpage?
This
Ok- what URL are you putting in your browser search bar to get to this page?
I mean, the page before that with the button to authorize
The example url, but o replaced client id with my client id and replaced the other data too
You need to generate the URL from the portal
Otherwise it won't match up and you'll get the error
K
I’ll do that in a bit I’m eating rn
@sick birch ?
Omfg ij realized your name is Bubger Kirg and not Burger King
!d discord.ForumChannel.threads
property threads```
Returns all the threads that you can see.
thats the joke :>
XD
so would this return all channel id or objects
Just like dad.exe rarely returns milk
ok
kinda conused can u show me an example of it
it's just channel.threads
Where channel is a forum channel
how do i get forum channel object
Hm
This site must have answers
(The answers are generated by AI)
get_channel like usual
Pass in the ID
Or you can type hint it to have users mention it
ok
It's just like getting a normal channel
just making sure
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)
!code
can someone help me?
Why is the page not working? Help 😮
why even create a one of list just do [str(message.content)] in the function
its gonna have only one item and is recreated everytime the event is triggered
its relative to main.py
😮
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
@sick birch sorry to ask but how do I get the emoji that was reacted to thread?
actually, its relative to keep_alive.py
@shrewd apex ?
One moment, I'll check docs again 😅
!d discord.Thread.starter_message
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.
You can check the reactions of this, it's just a regular message object
u thinnk I can check amount with this
Yeah same way you'd check reaction count for normal messages
should I use quart instead of flask or can flask fix this
Quart isn't going to solve that
Then what will?
Not sure, sorry. I don't use replit as a web server
@sick birch how would I do fetch message from thread?
same way you fetch message from normal channels
threads are pretty much indistinguishable from regular old text channels so just treat them as such
try ./index2.html or templates/index.html play around with the paths
I think it still create a list with just one value, which isnt what i wanted, im looking for a way to add the content of two different message (question and response) into a list, unless you can somehow combine two list (a list with a single question str, and a list with a single response str) from two different function
for that u need to create a list / dictionary outside the function
so it dosent get overriden everytime the event ocvurs
I fixed it, but ran into another issue. I’ll ask for help in the morning cause I’m tired and brain.exe has stopped working
holy sh*t it worked, thank you!
🫡
!d discord.InteractionResponse.defer
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...
!d discord.ext.commands.Bot.get_all_members
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
How are there music bots when using youtube is illegal
There are many other sources of music than just YouTube
ik you..you the guy from topgg
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
#965291480992321536 pinned messages
you should ask if there are any worse options than repl.it
i can help but you have to watch ads + ur bot must be written on js
bummer, my bot running on python 💀
aah...
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...
ty for the info, maybe it will useful in the future
yeah ...hoping so :)
daki
So I am using jupyter notebooks and my jupyter notebook showing this,now idk what to do tbh!
seems like coursera issue with web browser client
why are u doing it over net tho can u not download the exercise and do it locally?
Not really,I have to do the excercise online
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
Broo
It worked ,what are you,god or something,i had been trying since freaking 2 hrs
What does the io error mean?
are u like topgg moderator 👀
input / output

oh rip when i thought i had back door auction pass 😔
not even in the server
You are in the topgg server but also not in the topgg server? Dang, that's one hell of a power
What are you on? Never said I was in it?
I'm talking about what Guy said
Erika

hmm how do u know? 
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?
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.
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
The application will be banned if reported.
That's been the case for ages and it doesn't change anything
Then how I managed to test nuke my own server and now I can't? Maybe I just dump.
skill issue

fr
you are supposed to use the Bot instance you created
im nooob
then why you start discord bot project
bot
OHHH KAYYYY
thoughts?
you know what yield does?
returns a generator object to the one who calls the function which contains yield
yes and you do that in a function that is a command
you never get those members you yield them outside the function
🚶
imma get some sleep
op conclusion
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
im not any python expert im just trying to learn
nope not saying anything particularly mocking except that was funny tbh
nah just need all member count in all the guilds on status
fr
that can be a python meme
if you need how many members does the guild have why you iterate over it
IIRC client.user gives you all the users your bot can see
!d 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").
You don't have to iterate over it twice
iterate means?
dam
loop over it
To loop over all items in a list
ohkay...
len(s) will give you the length of some iterable s
like say u have a basket of apples u take them out and count them one by one showing it
*dissapointmet at its peak
lousy example but thats the gist
oh thats so dumb
and client.users or bot.users or whatever you have will return an iterable of all the members - you can probably see how to put those together to get the total member count
np
yeah when u could just call len() on the basket :p
len(client.users)
pro
there you go
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
yeah and does it work?
idk
so try
!d discord.ext.commands.Context.send
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...
okay?skill issues for ctx
true
should be str type so should raise exception
guys!!!
the command is working but....
it says 4k + member
but bot in only in my server
with 48 members
how it is possible
???
your getting the users across all of its servers
47k is way more than 4k
oh damm 47k+
print to console bot.guilds
check how many servers its in
but how?
len(bot.guilds)
you want the length of the members attribute of the guild the command is being sent from
what

u im here on phone
fr
any sol. for that 47k+ usrs
discord gods helped me to grow my bot
what you want to achieve?
success
.. with such answers im not able to help you solve your problem
all the members in all the guilds
i dont know its your bot
i dont know
what is illegal about bot seeing 47k members
he just started coding it?
so how long have u been coding?
i dont know but its clearly his first bot based on his first question xd
then i left
and u didnt know what an iterable was?
no
hmm
i code in bd
sounds sus 
earlier
you code for 2 years and dont know OOP??
fr
dam you code 5min a day or what
whats bd
ik OP overpowering
over powered
ik ez
BDScript
bd is short for bed
so its like some js spin off?
UK what cd is short form of?
change directory
ok you still need help about discord bots cause this is getting out of this channel topic
someone made a language for discord bots

f damn
thats the best thing u said all day 🫡
learn a bit more of python if you want to dive into discord bots
we dont need any more languages ending with script
compliment? or ...
js is enough ts is way to
compliment
oh fine
cause you are missing few imporant ones like
- OOP
- functions
- async stuff
ik def
def is not what functions have to offer
async means to sync smth ?
no
asynchronous
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.
intresting...i completely understand
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.
ik to make api requests and formate them so someone can read it
i made a bot with perspective api shit that somehow works
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.guilds
I followed what this said and the commands still aren't showing up in the guild
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
Yes
do you load the cog
No, there isn't. I get an error saying it's not valid
Yes, it's already loaded
there is not built in you have to create your own yes
but the one from commands wont work in slash commands
!d discord.app_commands.check
@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...
is has a nice example
Ok, but what about the reason I'm here?
share the cog code
Why do you need to see the entire cog?
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
do you sync the command tree?
Yes
In a different cog, using ctx.bot.tree.sync()
so you have a command to sync ?
Yes, 46 sync, these two don't
try passing the guild id to the sync
so it is supposed to be global?
well then it can take up to an hour to register global commands
This did nothing
is there a posibility you sync the commands before cog is loaded?
No
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?
Im back and I still need help with the token pull request
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.
Thank you so much!
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
!d discord.app_commands.autocomplete
@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...
i read that, unfortunately i'm not getting any error and the autocomplete doesn't seem to be working
And i dont understand how that can work with slash commands as i have to change the decorator
what code did you try writing? autocomplete's purpose is to provide choices for a slash command's option while the user types
though personally i prefer implementing autocomplete by subclassing Transformer
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.")
