#discord-bots
1 messages · Page 190 of 1
ah no it's not on the stdlib
requests is not a stdlib package, that's urllib.requests, requests is 3rd party
!d urllib.request
Source code: Lib/urllib/request.py
The urllib.request module defines functions and classes which help in opening URLs (mostly HTTP) in a complex world — basic and digest authentication, redirections, cookies and more.
It is
I mean makes sense since mimetype need the actual file.
Also mimetypes won't "guess", it's a way to verify an extension reliably.
await bot.change_presence()
Finally I can get a reaction in this channel.
😬
this channel has got fairly inactive after Aug 28, 2021
what are those random spikes
Well those spikes since the X axis is so small in comparison to the timeline. Those are most likely public holidays. Since most people here are younger than the rest of the average age.
Could be numerous things.
2020, 2021, 2022?
2021
@slash_command(name='giveaway')
async def giveaway(self, interaction: Interaction):
return
@giveaway.subcommand(name='start')
...
AttributeError: 'SlashCommand' object has no attribute 'subcommand'. Did you mean: 'is_subcommand'?
i am using pycord
examples/app_commands/slash_groups.py lines 14 to 20
math = discord.SlashCommandGroup("math", "Commands related to mathematics.")
@math.command() # Create a slash command under the math group
async def add(ctx: discord.ApplicationContext, num1: int, num2: int):
"""Get the sum of 2 integers."""
await ctx.respond(f"The sum of these numbers is **{num1+num2}**")```
Can you make embeds without value field?
embed = discord.Embed(title=" Please wait while the bot is balancing the teams.", color=discord.Color.black())
message = await ctx.send(embed=embed)```
no
why don't you just use the description?
also, you can use an empty field add_field(name="name", value="\u200b")
I have a cog and for some reason it doesn't connect to the main, can someone help me please?
What about this?
embed = discord.Embed(title="", description=" Please wait while the bot is balancing the teams.", color=discord.Color.black())
message = await ctx.send(embed=embed)```
Unresolved attribute reference 'black' for class 'Colour'
Black doesn't exist? 🤔
Should I just use discord.Color.default?
discord.Color(0) would work too, or 0
What is discord.Color.default? Does that equal to black?
!d discord.Colour.default
classmethod default()```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") with a value of `0`.
0 as in the hex value 0x000000, meaning 0 red, 0 green, and 0 blue, so black
Understood
What is wrong with this code?
# Check if the user is already in the queue
if member not in queue:
# Add the user to the queue
queue.append(member)
# Send a message to the channel
channel = discord.utils.get(member.guild.text_channels, id=712074759453671494)
embed = discord.Embed(title=f'{len(queue)} players are currently in the queue',
description=f'{member.mention} has been added to the queue.',
timestamp=datetime.datetime.now(), color=discord.Color.blue())
await channel.send(embed=embed)```
I can't use await channel.send(embed=embed)?
What's the problem with it
I'm getting Unexpected argument and Parameter '__value' unfilled
show full traceback
Imagine not using get_channel
channel = discord.utils.get(member.guild.text_channels, id=712074759453671494)``` ❎
```py
channel = guild.get_channel(712074759453671494)
yeah i was typing that lol
Thanks
Living ded found
please help, i get this error when trying to load another file from a folder: bot.load_extension("Mining_bot_commands.Mining_help")
discord.ext.commands.errors.ExtensionFailed: Extension 'Mining_bot_commands.Mining_help' raised an error: TypeError: The command passed must be a subclass of Command
OHH i named a variable badly
How to fix this
File "C:\Users\user\Downloads\Anya bot pls work\main.py", line 9, in <module>
bot = commands.Bot (command_prefix='/')
TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'
!intents
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.
Is there a way to change position of voice channel using bot?
i dont believe so
no
VCs are always shown at the last
I think they meant the order of the VCs in itself but yeah the answer is still no
!d discord.abc.GuildChannel.move
await move(**kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A rich interface to help move a channel relative to other channels.
If exact position movement is required, `edit` should be used instead.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to do this.
Note
Voice channels will always be sorted below text channels. This is a Discord limitation...
They will be behind the text channels but can me re-ordered within themselves ig
Go fuck yourself
Hi yall! I'm making a ticket system, and I have a problem with a piece of code that ensures that a user can't create multiple tickets in the same category.
Code:
`existing_channels = [channel for channel in guild.text_channels if channel.name.startswith(f"{category}-{author}")]
if existing_channels:
ticketwarn = await ctx.send(f"You already have a `{category}` ticket open, please use that instead! {user.mention}!")
await asyncio.sleep(3)
await ticketwarn.delete()
return`
this is before it creates a text channel btw
the ticket channel name format is {category}-{author}
However it does not prevent me from creating multiple tickets in the same category. What could be the issue with it?
Can we see where author and category are defined?
a category and a user variables are passed to the tickethandler function, I get author by doing author = str(user)[:-5], the category is defined in the function that listens for reaction, and is passed like this:
if reaction.emoji == "1️⃣":
category = "Owner"
elif reaction.emoji == "2️⃣":
category = "Donate"
elif reaction.emoji == "3️⃣":
category = "Other"
await message.remove_reaction(reaction.emoji, user)
asyncio.create_task(tickethandler(ctx, category, user))
both category and user are correct, because they are used in the title of the ticket channel
I tried printing the category and the author variables for debug but they are correct, and are what they are supposed to be
How can I solve the error message Local variable 'thumbnail_url' might be referenced before assignment?
for rank, url in rank_to_thumbnail.items():
if tier_and_rank.startswith(rank):
thumbnail_url = url
break
if thumbnail_url:
embed.set_thumbnail(url=thumbnail_url)
await ctx.channel.send(embed=embed)```
I'm getting the error because its inside the loop
thumbnail_url
this error happens when thumbnail_url might not be defined by the time you're using that var, because if your if statement there is never true, its not gonna be defined, so you need to define it outside the for loop, ```py
thumbnail_url = None
for ... in ...:
...
if thumbnail_url:
...
Thanks. How can I make this code easier to understand?
rank_to_thumbnail = {
"Iron": "https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-iron.png",
"Bronze": "https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-bronze.png",
"Silver": "https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-silver.png",
"Gold": "https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-gold.png",
"Platinum": "https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-platinum.png",
"Diamond": "https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-diamond.png",
"Master": "https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-master.png",
"Grandmaster": "https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-grandmaster.png",
"Challenger": "https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-challenger.png",
}
thumbnail_url = None
for rank, url in rank_to_thumbnail.items():
if tier_and_rank.startswith(rank):
thumbnail_url = url
break
if thumbnail_url:
embed.set_thumbnail(url=thumbnail_url)
await ctx.channel.send(embed=embed)```
um
whats the example string for tier_and_rank? 
whats the point of that dict if you're gonna iterate through it
Can't I use thumbnail_url = https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/{grab_from_the_list}.png
Then use emblem-challenger if starts with Challenger
Silver 1, Silver 2, Gold 4 etc
oh, couldn't you just split it then by space, get the first word
Tier = Iron-Challenger
Rank = 1-4
You should just get the first word and use a dictionary lookup then
i dont think dict a necessary, could just lower the word, and then do f-string with the url
Yes the URLs are very conveniently named
But if you're in a situation where you're using a dictionary solely for iteration, chances are you should use a list of tuples instead, dicts consume much more memory
since the pattern is like that, you can use str.partition with space, lower it, then f-string with your url, ```py
rank, *_ = tier_and_rank.partition(" ") # first occurance split
lowered_rank = rank.lower() # lower-case
url = f'https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-{lowered_rank}.png' # basic f-string
should be fine since the only thing i see that changes in your url is the name
You are a genius
rank, *_ = tier_and_rank.partition(" ") # first occurance split
lowered_rank = rank.lower() # lower-case
thumbnail_url = f'https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-{lowered_rank}.png' # basic f-strin
if thumbnail_url:
embed.set_thumbnail(url=thumbnail_url)
await ctx.channel.send(embed=embed)```
the if statement is kinda redundant since its always gonna be truthy
Not if they are Unranked
yea you might wanna check the rank instead of thumbnail_url if thats the case
How do I do that?
check if the rank are valid in your predicate? its totally up to you, i dont know every single thing about your 'rank' unfortunately
if lowered_rank == 'unranked':
pass```
What do you think about this?
rank, *_ = tier_and_rank.partition(" ")
lowered_rank = rank.lower()
if lowered_rank == 'unranked':
pass
else:
thumbnail_url = f'https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-{lowered_rank}.png'
embed.set_thumbnail(url=thumbnail_url)
await ctx.channel.send(embed=embed)```
personally i would do like lowered_rank and lowered_rank != 'unranked', so that i check if lowered_rank is not empty or if its not unranked
doing if-else is not pretty
welcome
Anyone know why I got this error message? It seems like I only got it once and I can't figure out why. discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'get_role'
# Get the custom games role
custom_games_role = ctx.guild.get_role(712084626201641070)
# Add the custom games role to the user
await user.add_roles(custom_games_role)```
ctx.guild returns None there, this happens if the command is invoked in DM
I think you are actually right. Someone must have run the command in the DMs. Do you know how I can solve this?
so how can I guess the file extension without saving the file ?
if you're using prefix command and you want it to be only be invoked in a guild, just set a commands.guild_only check so they can only invoke it in a guild
@commands.guild_only()
I'd like to do the filter before py for ... In ... Because if the bot doesn't find a .jpg image it retries
AttributeError: 'function' object has no attribute 'guild_only'
Should I use it like this?
@client.command(name = 'setup')
@commands.guild_only()
async def setup(ctx, *, summoner_name: str=None):```
yes
@commands.guild_only()
AttributeError: 'Command' object has no attribute 'guild_only'
you have a command named commands that is shadowing discord.ext.commands
alternatively you should name your function as something else and use name kwarg to rename, py @client.command(name='commands') async def _commands(...): that way it doesnt overshadow your discord.ext.commands
Now I have to add a error handling for discord.ext.commands.errors.NoPrivateMessage: This command cannot be used in private messages.
ye
truthfully i would handle commands.CheckFailure and show the error directly to the user, this cover for all check errors
hey i need some help
TypeError: cogs must derive from Cog
import discord
from discord.ext import commands
import json
import os
import asyncio
# Get configuration.json
with open("configuration.json", "r") as config:
data = json.load(config)
token = data["token"]
prefix = data["prefix"]
owner_id = data["owner_id"]
intents = discord.Intents.default()
bot = commands.Bot(prefix, intents = intents, owner_id = owner_id)
async def loadcogs():
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await bot.load_extension(f'cogs.{filename[:-3]}')
async def main():
await loadcogs()
await bot.start(token)
asyncio.run(main())```
```py
import discord
from discord.ext import commands
class misc(commands.Cog):
def __init__(self,bot):
self.bot = bot
@commands.command()
async def ping(self,ctx):
await ctx.send('pong')
async def setup(bot):
await bot.add(misc)
full traceback?
Exception has occurred: ExtensionFailed
Extension 'cogs.misc' raised an error: TypeError: cogs must derive from Cog
File "C:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot\cogs\misc.py", line 21, in setup
await bot.add_cog(misc)
TypeError: cogs must derive from Cog
The above exception was the direct cause of the following exception:
File "C:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot\main.py", line 21, in loadcogs
await bot.load_extension(f'cogs.{filename[:-3]}')
File "C:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot\main.py", line 24, in main
await loadcogs()
File "C:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot\main.py", line 27, in <module>
asyncio.run(main())
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.misc' raised an error: TypeError: cogs must derive from Cog
Can we see your cog?
its there
misc is a class there, you need to instantiate ```py
await bot.add_cog(misc(bot))
also you should name your classes with PascalCase
Oh didn't see that
Can I add this for all commands instead of adding it for each command?
i will try it
do it in a global error handler
Exception has occurred: ExtensionFailed
Extension 'cogs.misc' raised an error: AttributeError: 'Bot' object has no attribute 'add'
bot.add_cog, bot.add doesn't exist
welcome
well i haven’t made anything yet im jus looking for someone to help me get it
You need to have a valid reason for message content to be granted to you
Would this do the work?
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CheckFailure):
await ctx.send("This command can only be used in a server, not in direct messages.")```
also do an else statement for other errors
it works, but it isnt correct, commands.CheckFailure covers for all check errors, not just guild_only errors
pro tip is that you would do await ctx.send(str(error)), casting your error to str will show the actual error message, this is usually what most people do for generalized errors
take a note on this as well, because you may ended up silencing your error
How can I specify it to only detect guild_only errors?
commands.NoPrivateMessage
So this is what I'm looking for:
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.NoPrivateMessage):
await ctx.send(str(error))
else:
# Handle other errors here
raise error```
sure
here's an example: https://gist.github.com/EvieePy/7822af90858ef65012ea500bcecf1612
ccog = interaction.client.get_cog(module)
if ccog is not None:
#Page of a choosen cog
emoji = getattr(ccog, "COG_EMOJI", None)
embed = nextcord.Embed(title=f"{emoji} __{ccog.qualified_name}__" if emoji else f'_{ccog.qualified_name}_',
description=f"{ccog.description or '...'}",
colour=config.blurple)
for cmd in ccog.application_commands:
embed.add_field(name=cmd.get_mention(),
value=f'{cmd.description or "..."}\n\uFEFF')
if cmd.children:
for sub in cmd.children:
embed.add_field(name=sub.get_mention(),
value=f'{sub.description or "..."}\n\uFEFF')
else:
pass
await interaction.edit_original_message(embed=embed)```
it does not find the subcommands
why i cant make requests in discord py ?
are you getting any error?
Who?
yes
even when i try to add images to an embed
Can you show the error
2023-02-02 19:45:22 ERROR discord.ext.commands.bot Ignoring exception in command None
Can you show the code
yes this is the error i get
when i try to use requests or even insert a image to an embed
Can you show the code though?
2023-02-02 19:45:22 ERROR discord.ext.commands.bot Ignoring exception in command None
@commands.command
async def boxen(self,ctx,member:discord.Member):
embed=discord.Embed(colour=0x40E0D0,title=f'{ctx.message.author.name} schlägt {member.name}')
embed.set_image('https://media.tenor.com/Lho_KrumiL4AAAAM/kevin-hasbu.gif')
await ctx.send(embed=embed)```
@commands.command()
oh
Can someone help?
Do you know what I can do with commands that doesn't exist? discord.ext.commands.errors.CommandNotFound: Command "onsetup" is not found
!d discord.ext.commands.CommandNotFound ignore this exception in yr error handler
exception discord.ext.commands.CommandNotFound(message=None, *args)```
Exception raised when a command is attempted to be invoked but no command under that name is found.
This is not raised for invalid subcommands, rather just the initial main command that is attempted to be invoked.
This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").
So like this?
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.NoPrivateMessage):
await ctx.send(str(error))
elif isinstance(error, commands.CommandNotFound):
pass # Do not handle this error and simply ignore it
else:
# Handle other errors here
raise error```
yes
hey gays, how it possible to reload VOSK module and model on runned program?
this wey
def reloadmodule(): importlib.reload(vosk)
ist work
who could help with message intents
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/aiohttp/connector.py", line 1175, in _create_direct_connection transp, proto = await self._wrap_create_connection( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/aiohttp/connector.py", line 982, in _wrap_create_connection raise ClientConnectorCertificateError(req.connection_key, exc) from exc aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:992)')]
any solutions?
Are you on MacOS?
yes
Go into your "Applications" folder in Finder, find the "Python" folder, double click "Install Certificates" or whatever it's called
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:992)'))': /simple/certifi/
it keeps spamming that
I'll retry
That's about the extent of my knowledge on debugging on Mac
still not working 😭
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/aiohttp/connector.py", line 1206, in _create_direct_connection raise last_exc File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/aiohttp/connector.py", line 1175, in _create_direct_connection transp, proto = await self._wrap_create_connection( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/aiohttp/connector.py", line 982, in _wrap_create_connection raise ClientConnectorCertificateError(req.connection_key, exc) from exc aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:992)')]
still the same error, if anyone can help Im on mac
Was this after you ran the install certificates file?
& Have you tried rebooting your mac
yes
yeah
Did you specifically install certificates for Python 3.11?
Like, you didn't accidentally install it on 3.10
yes I did
so help me 💯
Do what?
message intents
Many bots don't require message intents at all. If it's your bot then you should have a clear idea of which intents it needs, and why.
Where's the documentation for buttons with discord.py?
So I was testing around with the fetch_invite() method and ran into an error of exceeding 6000 characters in an embed, but I shouldnt be getting that error. So I made a test command and it still gives me the error of exceeding the 6000 limit. Here is the test command:
@client.command(name='vanitytest')
async def vanitytest(ctx, *, url=None):
await ctx.message.delete()
user = ctx.author
if user.id == ownerID:
embed = discord.Embed(colour = discord.Colour.red(),)
try:
result = await client.fetch_invite(url)
embed.add_field(name=url, value='Valid', inline=False)
except discord.NotFound:
embed.add_field(name=url, value='Invalid', inline=False)
return await ctx.send(embed=embed)
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed: Embed size exceeds maximum size of 6000
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
what's the best way to set them up?
Subclass the view object
mehh
guys how do i make my bot update a message everyday? Like maybe an embed with the date in a separate locked channel that i wanna update like a calendar everyday?
How do you check if the button was pressed?
The callback
use datetime and after every 24 hours passes edit the original message/delete and resend
alright!
Wdym
!d discord.ui.Button.callback
await callback(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The callback associated with this UI item.
This can be overridden by subclasses.
wheres te examples again
It's literally in the official GitHub
https://github.com/Rapptz/discord.py/tree/master/examples/views
Try to look for yourself for once
sorry Idk how to use google
cannot import name 'InvalidArgument' from 'discord'```
from discord_slash import SlashCommand```
SlashCommand no longer supported
See examples on github how you can create slash commands
He's saying to not use SlashCommand.
Its outdated right now you need to use app_commands

who knows jadi mirmirani?
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
I created an economy bot with mongodb but for the bot verification i need my users to be able to get their data deleted. I just cant figure out how i could do this.. Can anyone help me?
Make a command for it..?
Who would have thought
Also pretty sure economy bots either don't delete it or delete it on guild leave event.
A cross guild economics bot could also delete if it is in no guild that uses the bot.
Its cross guild but i cant figure out how to delete the user ids of the people. For inventory for example
How do you save them?
i used someone else their code and then changed a few things
Im not that good at coding so i just dont know how i could create a command that wipes the entire id and inventory
Looked at docs, MongoDB confuses me, maybe someone at #databases knows?
nvm
can someone help
i keep getting this
prediction_grid[int(prediction[count])] = ':good:'
Traceback (most recent call last):
File "/home/runner/Auth/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 130, in auth_mines
prediction_grid[int(prediction[count])] = ':good:'
ValueError: invalid literal for int() with base 10: ' '
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Auth/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/Auth/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/Auth/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'paid_pattern_mines' raised an exception: ValueError: invalid literal for int() with base 10: ' '
full trace back
@shrewd fjord
!e int(" ")
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ValueError: invalid literal for int() with base 10: ' '
" " is not an integer
!code
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.
so im trying to do that if someone sets a role with database so it will save it and everytime they will run a specific command i made itll mention the role, how do i start does anyone have tutorial or example
https://paste.pythondiscord.com/azobehodoy thats what i did
Please be more specific.
Try if it works, we'll help if there's a problem.
Tias
Like they run the command !set_role @rolemention
Yes
and then when they run like !h so its pinging the role
yes
oh
like i did that for now https://paste.pythondiscord.com/lozedufaha
yes did that
Yes cool
await cursor.execute("CREATE TABLE IF NOT EXISTS role (guild INTEGER, role_id INTEGER)")
Yes too good
Now do is on set_role command try doing this
await cursor.execute(f"SELECT role_id FROM guild WHERE guild = {ctx.guild.id}")
data=await cursor.fethone()
if data is None:
#here u r going to insert values
then
#if it doesnt return None
else:
#update the role id on the database
Commit the changes and close connection as well as db
oh i did that
ill try
oh
what do i have to do now then?
oh
else:
await ....
await cursor.close()
await db.commit()
await db.close()```
fdid that
the else should be above cursor.close()
What is !h then?
They both automatically closed after the context manager block ends
Oh yeah lmao
should be mentioning the role they set in !set_role
I forgor, f, i am actually used to sqlite3 not aiosqlite aand idk what's my problem to use asynchronous lib 💀
Ok wait
if data:
await cursor.execute('UPDATE role SET role_id = ? WHERE guild = ?', (ctx.guild.get_role, ctx.guild.id,))
else:
await cursor.execute('INSERT INTO role (role_id, guild) VALUES (?, ?)', (ctx.guild.get_role, ctx.guild.id,))```
Why this thing exist on !h then?
They're the exact same, just aiosqlite is async binding
Yea ik, just too lazy to migrate to aiosqlite and change code a bit 🗿
Ok so
On !h
you should be fetching the datas not changing them
so if data:
#means the role_id exists...
so just do this
oh right!
I need someone to help me solve one command.
In return, I can pay because I can't stand it mentally anymore. If anyone wants more details send me a dm.
Just ask your questions
Then use get_role method
No need to pay or anything 
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
tysmmm
I am on it 
So u can now get the role role obj easily with this method and just now use role.mention to ping it or whatever
Also if data returns None then tell them to do set_staff first and set a role
Kinda ez imo
is that good?
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT role_id FROM role WHERE guild = ?', (ctx.guild.id,))
role_id = await cursor.fetchone()
if role_id:
if not role_id[0] == 1:
return```
Why are you selecting twice
oh oops
whats == 1 for?
if data:
em = nextcord.Embed(title="Leveling LeaderBoard", color=0x88e86f)
count = 0
for table in data:
count += 1
user = ctx.guild.get_member(table[2])
em.add_field(name=f"{count}. {ctx.author.name}#{ctx.author.discriminator}", value=f"Level - **{table[0]}** | XP - **{table[1]}**", inline=False)
return await ctx.send(embed=em)
return await ctx.send("There Are No Users In The LeaderBoard 😢 ")``` smt like that now? did that in my old code-
No 💀
it's kinda correct
Just
if role_id:
role=ctx.guild.get_role(role_id[0])
This is how u get the obj
oh not if role_id:
if not role_id[0] == 1:?
Nope
Wait 🗿
@shrewd apex or @naive briar
Is it going to return list?
Or directly going to return the jd
Id*, i kinda forgot
Tuple
Oh yeah
its indexable so dosent matter lol
Doesnt matter but imagine doing
guild.get_role(role_id)
And role_id returns tuple 💀
unpack it or make a dataclass
!paste
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.
So far so good except
role = get_role(role_id**[0]**)
maybe ill change it later
oop- it shows an error
File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 402, in <module>
async def invite(interaction: nextcord.Interaction):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 1399, in decorator
result = command(name=name, cls=cls, *args, **kwargs)(func)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 1660, in decorator
return cls(func, name=name, **attrs) # type: ignore
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 316, in __init__
raise TypeError("Callback must be a coroutine.")
TypeError: Callback must be a coroutine.```
The ss please 🗿
I wonder why
even if i put as an # it shows an error on a dif command
Code
@bot.command()
async def set_staff(ctx):
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT role_id FROM role WHERE guild = ?', (ctx.guild.id,))
data = await cursor.fetchone()
if data:
await cursor.execute('UPDATE role SET role_id = ? WHERE guild = ?', (ctx.guild.get_role, ctx.guild.id,))
else:
await cursor.execute('INSERT INTO role (role_id, guild) VALUES (?, ?)', (ctx.guild.get_role, ctx.guild.id,))
await cursor.close()
await db.commit()
await db.close()
class MyButton(nextcord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.value = None
@nextcord.ui.button(emoji=":NoaOkay:", label="Claim", style=nextcord.ButtonStyle.green,custom_id="myButton")
async def my_button(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
if interaction.permissions.manage_messages == False:
return await interaction.response.send_message(content="**Only staff can claim this helpme!**", ephemeral=True)
button.disabled = True
button.label = f"Claimed by - {interaction.user.name}#{interaction.user.discriminator}"
await interaction.response.edit_message(view=self)
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
embed = nextcord.Embed(title="Error ", description='**  You have cooldown, please try again in `{:.2f}` seconds!**'.format(error.retry_after))
await ctx.send(embed=embed, delete_after=4)
else:
raise error
@bot.command(aliases=["H", "helpme", "Helpme"])
@commands.cooldown(1,60,commands.BucketType.user)
async def h(ctx, *,message='No reason provided '):
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT role_id FROM role WHERE guild = ?', (ctx.guild.id,))
role_id = await cursor.fetchone()
if role_id:
role = ctx.guild.get_role(role_id[0])
check = ctx.author.voice
if check is None:
voice = f'Not in a VoiceChannel '
else:
voice = ctx.author.voice.channel.mention
emeb12233 = nextcord.Embed(description=f'{ctx.author.mention} - Needs your help !  ',color=0x6c97c5)
emeb12233.add_field(name="__**Reason:**__", value=f'{message}', inline = False)
emeb12233.add_field(name="__**Room:**__", value=voice, inline = False)
emeb12233.add_field(name="__**User:**__", value=ctx.author.mention, inline = False)
emeb12233.set_footer(icon_url=ctx.author.avatar, text=ctx.author.name + "#" + ctx.author.discriminator,)
emeb12233.set_thumbnail(url=ctx.author.avatar)
await ctx.send("<@&" + role + ">", embed=emeb12233, view=MyButton())
@bot.command()
async def uytsgad7ygs9ahyd7sa67tfdsayhduasyuhdjsa6sya(ctx):
view = MyButton()
await ctx.send(view=view)```
Why are you passing get_role meth as a value
Yeah i wonder too, like why u did so much work xd
and taking it so i can do await ctx.send("<@&" + role + ">", embed=emeb12233, view=MyButton())
U can directly do f"{role.mention}"
also an option yes
Or just role.mention 🐈
Full traceback
ctx.guild.get_role bc of that right
...
what do i do instead just ctx.get_role
No?
oh then
ctx.guild.get_role to be exact
One bad thing can happen is, if the role doesnt exist get_role will return None
Make sure to handle it :)
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
if they mention a role that doesnt exists?
like !set_staff @hadsysysds
No think of they set the correct role but somehow today they decided to delete the role
So yeah
ohh
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 165, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 60, in set_staff
await cursor.execute('INSERT INTO role (role_id, guild) VALUES (?, ?)', (ctx.guild.get_role, ctx.guild.id,))
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 129, in _execute
return await future
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 102, in run
result = function()
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 512, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 491, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1381, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 948, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 174, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: InterfaceError: Error binding parameter 0 - probably unsupported type.``` full error
yesyes tysmsmsmms
If any error i am here to get ur back or catglal xd
AttributeError: 'NoneType' object has no attribute 'id'
role is probably None
so i have a question
im trying to make a command
which can trigger midjournes command /imagine prompt
it sends out the message yeah, but it doesnt trigger midjourneys command
if message.content.startswith("$Midjourney"):
midjourneyPrompt = " ".join(message.content.split()[1:])
print(f"midjourneyPrompt: {midjourneyPrompt}")
original_channel = message.channel
target_channel_id = 1071107593692528660
target_channel = bot.get_channel(target_channel_id)
await target_channel.send(f"/imagine {midjourneyPrompt}")
target_channel_response = await bot.wait_for('message', check=lambda m: m.channel == target_channel and m.attachments)
image_url = target_channel_response.attachments[0].url
midjourney_response = requests.get(image_url)
await original_channel.send(file=discord.File(io.BytesIO(midjourney_response.content), "midjourney.png"))
time.sleep(2)
os.remove("midjourney.png")
i did it also as an id and everything
wdym?
that's not how you trigger commands
wdym by role is none? that i didnt mention a role or smt wrong w the code
you simply can't write slash commands as normal messages
how are you getting the role variable
i dont rlly understand ur question
then how could i trigger midjourneys command?
it's a slash command?
yessir
from where are you getting the role variable for role.id
oh, py @bot.command() async def set_staff(ctx, role: nextcord.Role): async with aiosqlite.connect("main.db") as db: async with db.cursor() as cursor: await cursor.execute('SELECT role_id FROM role WHERE guild = ?', (ctx.guild.id,)) role = await cursor.fetchone() if role: await cursor.execute('UPDATE role SET role_id = ? WHERE guild = ?', (role.id, ctx.guild.id,)) else: await cursor.execute('INSERT INTO role (role_id, guild) VALUES (?, ?)', (role.id, ctx.guild.id,)) await ctx.send(f"Successfuly set the helpme staff role to - {role.mention}") await db.commit()
there the role
and you're trying to trigger it from a slash command?
like where you get journeyWhatever variable
ye
so when i write /imagine press space then appears like a prompt box
for some reason the script cannot trigger that
ah, i see, you shouldn't name these variables same
oh
idk how slash commands can be invoked 💀
sorry
oh.
ty ill try now
like
do i change it or what
name, the var name
hm, you could do that
Sorry for being off topic. But how did you add that type of border for the image?
oh no worries! ShareX
Looks cool is it some kind of preset or did you create it yourself?
Its an option there you can look at a tut
Thanks 
How to do auto update the stuff after someone updates the bot for their server?
hey guys! i use an orm for postgres db. any how can i add a column to a table without needing those migration versions? its a one time thing
how do you accept file from user
So I was testing around with the fetch_invite() method and ran into an error of exceeding 6000 characters in an embed, but I shouldnt be getting that error. So I made a test command and it still gives me the error of exceeding the 6000 limit. Here is the test command:
@client.command(name='vanitytest')
async def vanitytest(ctx, *, url=None):
await ctx.message.delete()
user = ctx.author
if user.id == ownerID:
embed = discord.Embed(colour = discord.Colour.red(),)
try:
result = await client.fetch_invite(url)
embed.add_field(name=url, value='Valid', inline=False)
except discord.NotFound:
embed.add_field(name=url, value='Invalid', inline=False)
return await ctx.send(embed=embed)
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed: Embed size exceeds maximum size of 6000
try printing the url to see how long it is
The thing is it was working just fine before I started adding more vanity URLS to check, even after reverting the code it still broke.
thats where we're at currently...
so you get an embed error despite there not being an embed sent here?
exactly 💀
do you have an on_message listener?
nothing more to it?
nope
i have no clue then, try asking in discord.gg/dpy
sounds good, appreciate the attempt
the error is coming from somewhere else where you tried to send an embed
Most probably because you have some event or task that does it
!paste send your full code
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.
https://paste.pythondiscord.com/ilinezitic @slate swan
ah lol
embed = discord.Embed(
colour = discord.Colour.red(),
title = f"Bot Error Found",
description = "User: {} | Error: {}".format(ctx.message.author.name, error)
)
```this could be the problem
errors can be quite long lol
especially dpy's
what's the full traceback?
str of error are not more than a line usually
but yeah that seems like the part where error comes from
now that i see the full traceback, i can assure you that the embed i sent above is the problem
use discord.py's default logging
or you can send the error in two seperate messages
@client.event
async def on_command_error(ctx, error):
channel = client.get_channel(1056704831051542653)
if isinstance(error, CommandNotFound):
print(error)
return
if isinstance(error, commands.BadArgument):
print(error)
return
if isinstance(error, commands.MissingRequiredArgument):
print(error)
return
if isinstance(error, commands.CommandOnCooldown):
await ctx.message.delete()
embed = discord.Embed(colour = random.choice(colors),title = "**ERROR: Cooldown Active!**",description = (f'You Are On Cooldown! You Can Use This Command In: {round(error.retry_after, 2)} seconds.'))
msg = await ctx.send(embed=embed)
await asyncio.sleep(6)
return await msg.delete()
if isinstance(error, CheckFailure):
print(error)
return
embed = discord.Embed(colour = discord.Colour.red(),title = f"Bot Error Found",description = "User: {} | Error: {}".format(ctx.message.author.name, error))
embed.set_footer(text="XIN Networks")
embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/788698131898171424/788702201832669194/XIN_GIF_3.1.gif')
return await channel.send(embed=embed)
mind giving me an example of that? @slate swan
yes but can you try printing the actual error that happened first?
before you tried to handle the exception
you might not need to do this if youre able to fix the main issue
💀 wall of text
you're ratelimited for that endpoint
Hello! I hope this message finds you well. I wanted to share with you a project that I've been working on. I recently created a Discord bot that I think could be a valuable addition to your server. It's designed to enhance the overall Discord experience with a range of helpful features. I would love for you to check it out and let me know what you think. If you're interested, you can find more information and add the bot to your server by visiting its GitHub repository. Thank you for your time, and I hope you enjoy the bot!
here is the github: https://github.com/LuciHusband/Outro-Bot 😄
would you happen to know any solutions to get around the fetch_invite() method rate limiting?
that endpoint has strict ratelimits so i won't suggest making a command that uses such
one workaround would be using multiple bot tokens and making a seperate web request with a random token out of those
not sure how id do that considering all of my other "node bots" are ran on the same server that appears to be limited
lol then respect the ratlimits 🙏
fair enough, thanks for the help lads @slate swan @naive umbra
got a error with webhooks
postData = {
"embeds":[
{
"title":"Escanor Stock Scraper",
"description":time,
"fields":[
{
"name":"Stock Link",
"value":f'https://finance.yahoo.com/quote/{stock.ticker}'
},
{
"name":"Stock Price",
"value":stock.price
},
{
"name":"Stock Fair Price",
"value":stock.fairPrice
},
{
"name":"Stock EPS",
"value":stock.eps
},
{
"name":"Stock Cashflow",
"value":stock.freeCashFlow
},
{
"name":"Stock PriceToIntrinsic Margin",
"value":marginOfFairness
}
]
}
]
}
postData = json.dumps(postData)
error code 400
with formatting
Get better
Hey I have a question. Would you be able to make a discord bot that gives users a role that allows them to access all channel after typing in a 5 digit code which I can generate.
However, they will lose their rank ever 24 hours, forcing them to type in the same code in order to regain access to the server.
I would also like to have the ability to change the code whenever I'd like.
Thanks.
It can be done
Though not sure about the 24 hour timer for every user in case you shutdown the bot for any reason
You have something so far?
Well that's something pretty advanced for a newbie
Maybe you should try to make a simpler function bot to get familiar
It'll help to avoid lots of mistakes later
sure
Proxies? 💀
How do I check if the person who pressed a button is the same as the person who invoked the command?
Store the user object in the class and check it
Can you do interaction.user.id I don't remember if that exists
Same thing
How do you allow multiple button presses? Like for example, non author presses button it allows the button to still be pressed
this should be the default behavior unless you manually disable the button when its clicked
oh yeah I forgot I added self.stop() lol
does anyone happen to know the color of an embed background in light theme?
sure
what is it?
i'll figure it out right now
oh thanks, how do you do it
#FFFFFF
nah its not that lol
yes it is
How can I only allow a command to be ran by the server owner? The deco only works for bot owner iirc
color picker
i literally color picked it from the discord website
nah thats the color of the background, not the embeds background
thanks for telling me color picker tho
its 0xF2F3F5
i see
Does member.flags still work?
It's throwing me a Member object has no attribute 'flags' error, but the docs say that it's an existing Attribute
where in the docs? I can't see it 
What docs are you looking at
https://discordpy.readthedocs.io/en/stable/api.html#discord.Member.public_flags there's this for stable
Those are the public flags, I wanted the member specific ones
Just sort it
huh?
2.2 is latest (github master) version
right
!d discord.PublicUserFlags
class discord.PublicUserFlags(**kwargs)```
Wraps up the Discord User Public flags.
There's a difference between the Public user flags, and the member specific flags, isn't there?
Public is for things like badges.
Member specific flags can tell you if the user has left and rejoined the server before. Which was what I'm trying to find.
Can you access a users date of birth without making your own database and asking for user input? Since discord requires it to make an account.
No
Rip 😢
i'm trying to make it so when someone uses /suggestion and the suggestion sends, a thread will be made by the bot on the message. i've almost got it, it currently does everything above except for make the thread on the suggestion. it creates it in the channel. here's my code
@bot.tree.command(name="suggestion", description="Sends a suggestion to our suggestion channel!")
async def _suggestion(interaction, suggestion:str):
channel = bot.get_channel(1059976520376012811)
suggestEmbed = discord.Embed(color=0xFF5349)
suggestEmbed.set_author(name=f'New suggestion by {interaction.user}', icon_url = f'{interaction.user.avatar}')
suggestEmbed.add_field(name='The suggestion is:', value=f'{suggestion}')
message = await channel.send(embed=suggestEmbed)
await message.add_reaction('✅')
await message.add_reaction('❌')
channel = bot.get_channel(int(1059976520376012811))
thread = await channel.create_thread(
name=f"{suggestion} Discussion",
reason="Suggestion",
type=discord.ChannelType.public_thread)
embed=discord.Embed(title=f"Discuss {interaction.user}'s suggestion!", color=0xFF5349)
embed.add_field(name="Like, dislike or want to add onto someones suggestion?", value="Do that here! In this thread, you can discuss what you like, dislike or something smiliar you'd like to see!", inline=False)
embed.set_author(name = f'{interaction.user}', icon_url = interaction.user.avatar)
await thread.send(embed=embed)
embed=discord.Embed(title="Successful!", color=0x23B425)
embed.add_field(name="This command was successful.", value="Your suggestion was successfully posted in [#1059976520376012811](/guild/267624335836053506/channel/1059976520376012811/)", inline=False)
await interaction.response.send_message(embed=embed)```
i run the command, everything works but as you can see it makes the thread in the channel rather the on the message
thats because you;re creating the thread in the channel, not the message
!d discord.Message.create_thread
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.
How do you set channel permissions? I thought it's just channel.set_permissions(role, perms)
so it'd be
type=discord.Message.public_thread)```
no.
you're using the wrong method
thread = await channel.create_thread(
``` means create a thread in channel ...
you should be using ```py
message.create_thread(
ok thanks
sarth yk right?
something like ```py
channel.set_permissions(role/member, permission_name=True/False)
where's the list of the permission names?
!d discord.Permissions
class discord.Permissions(permissions=0, **kwargs)```
Wraps up the Discord permission value.
The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.
Changed in version 1.3: You can now use keyword arguments to initialize [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") similar to [`update()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.update "discord.Permissions.update").
check the attrs of this class, those are perm names
do i need thread = await still?
yep
so it'd be?
channel = bot.get_channel(int(1059976520376012811))
thread = await message.create_thread(
name=f"{suggestion} Discussion",
reason="Suggestion",
type=discord.Message.public_thread)```
or would it still be
type=discord.ChannelType.public_thread)```
oh i dot need type
thank you so mucch, i spent so long on that and couldn't figure it out lol
@slate swan How do you get the everyone role object
!d discord.Guild.default_role
property default_role```
Gets the @everyone role that all members have by default.
or Guild.get_role(Guild.id)
File "main.py", line 96, in <module>
async def _kick(interaction, member: discord.Member, *, reason='None'):
File "/home/runner/kas/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 889, in decorator
command = Command(
File "/home/runner/kas/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 685, in __init__
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
File "/home/runner/kas/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 390, in _extract_parameters_from_callback
raise TypeError(f'parameter {parameter.name!r} is missing a type annotation in callback {func.__qualname__!r}')
TypeError: parameter 'reason' is missing a type annotation in callback '_kick'```
you need to typehint every param in a slash command
what does that mean- 😭 i only started making slash commands recently, i used to just make normal commands
def function(a: str, b: int):
...
``` telling the type of arguments in a function
ohh ok
you might have done something like ```py
async def command(ctx, member: discord.Member)
it's the same thing
@slate swan sometimes the /suggestion commands works and sometimes it doesnt, when it doesnt, i keep getting this error
File "/home/runner/kazue/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 83, in _suggestion
thread = await message.create_thread(
File "/home/runner/kazue/venv/lib/python3.10/site-packages/discord/message.py", line 1207, in create_thread
data = await self._state.http.start_thread_with_message(
File "/home/runner/kazue/venv/lib/python3.10/site-packages/discord/http.py", line 744, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In name: Must be 100 or fewer in length.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/kazue/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/kazue/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/kazue/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'suggestion' raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In name: Must be 100 or fewer in length.```
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
Read the docs
can anyone help me with this ^
Read the error, threads' names cannot be more than 100 characters
ohhh ok
guys can somebody just give me a basic boilerplate for bot?
i just need sample code with the imports and the token line and just one / command that replies with "hello"
which library?
nextcord or pycord is popular at the moment right?
@bot.tree.command(name="help", description="Provides you with the help embed!")
async def _help(interaction):
embed=discord.Embed(title="Help Menu", description="To find the help you're looking for, look below in this embed for whatever you need help with!", color=0xFF5349)
embed.add_field(name="**__General Commands__**", value="Everyone can use these commands, abusing them will result in punishment.", inline=False)
embed.add_field(name="``/help``", value="Provides you with this embed.", inline=False)
embed.add_field(name="``/suggest``", value="Sends a suggestion to [#1059976520376012811](/guild/267624335836053506/channel/1059976520376012811/).", inline=False)
embed.add_field(name="**__Moderation Commands__**", value="Staff with the correct permissions can use these commands. The following commands will be logged.", inline=False)
embed.add_field(name="``k!purge``", value="Purges the specified amount of messages.", inline=False)
embed.add_field(name="``k!kick``", value="Kicks the specified user with the reason.", inline=False)
embed.add_field(name="``k!ban``", value="Bans the specified user with the reason.", inline=False)
embed.add_field(name="``k!unban``", value="Unbans the specified user with the reason.", inline=False)
embed.add_field(name="``k!mute``", value="Mutes the specified user with the reason and amount of time.", inline=False)
embed.add_field(name="``k!unumte``", value="Unmutes the specified user with the reason.", inline=False)
embed.set_author(name = f'{interaction.user}', icon_url = interaction.user.avatar)
await interaction.response.send_message(embed=embed)```
was wondering if anyone could help me make those page buttons or even select menus like at the bottom of the carl bot help message. i've tried like literally everything, no clue how it works
whatever works best really
for slash commands: https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py
thanks king
wait isn't discord.py out of date?
discord.py has been discontinued for ages
oh wait it resumed
i've got some where, just not sure how to make the embed show depending on what you select
Edit the embed
!d discord.InteractionResponse.edit_message
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=..., delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by editing the original message of a component or modal interaction.
import discord
import random
intents = discord.Intents.all()
client = discord.Client(intents=intents)
tree = discord.app_commands.CommandTree(client)
@client.event
async def on_ready():
await tree.sync(guild=discord.Object(id=Your_guild_ID_here))
print("ready")
@tree.command(name="truth", description="Selects a truth from the td.txt file.")
async def truth(int: discord.Interaction):
with open("td.txt", "r") as f:
truth_dare_lines = f.readlines()
truth_lines = [line for line in truth_dare_lines if line.startswith("truth:")]
selected_truth = random.choice(truth_lines).strip()[7:]
await int.response.send_message(f"Truth: {selected_truth}")
@tree.command(name="dare", description="Selects a dare from the td.txt file.")
async def dare(int: discord.Interaction):
with open("td.txt", "r") as f:
truth_dare_lines = f.readlines()
dare_lines = [line for line in truth_dare_lines if line.startswith("dare:")]
selected_dare = random.choice(dare_lines).strip()[5:]
await int.response.send_message(f"Dare: {selected_dare}")
@tree.command(name="tod", description="Selects either a truth or a dare from the td.txt file.")
async def tod(int: discord.Interaction):
with open("td.txt", "r") as f:
truth_dare_lines = f.readlines()
truth_lines = [line for line in truth_dare_lines if line.startswith("truth:")]
dare_lines = [line for line in truth_dare_lines if line.startswith("dare:")]
if random.choice([True, False]):
selected_truth = random.choice(truth_lines).strip()[7:]
await int.response.send_message(f"Truth: {selected_truth}")
else:
selected_dare = random.choice(dare_lines).strip()[5:]
await int.response.send_message(f"Dare: {selected_dare}")
client.run("your_discord_bot_token_here")
Not working can someone tell why
Like slash command not appearing
are you sure you have a valid guild id?
yes
i have it written like this:
await tree.sync(guild=discord.Object(id=1035927785652359299))
synced = await tree.sync(guild=discord.Object(id=Your_guild_ID_here))
print(f"Synced {len(synced)} commands")
``` you might want to add a print like that to debug
"synced" is not defined
define it, tree.sync returns the commands that were synced
)
^
SyntaxError: unmatched ')'```
code:
ah wait
^^
exactly what i did. check second line in screenshot
.
hmm
Read the error
cuz that's what you sent here
oh wait ah. bro lemme fix.
"synced zero commands"
do i just turn the bracket from ) to (?
might want to try readding your bot to the guild (make sure you have the application.commands scope)
No, it's unmatched, remove it
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 1
002 | blahblahblah =
003 | ^
004 | SyntaxError: invalid syntax
do you mean like this?
@client.event
async def on_ready():
for guild in client.guilds:
if guild.id == 1035927785652359299:
synced = await tree.sync(guild=guild)
print(f"Synced {len(synced)} commands")
break
wait no
Just sync globally at this point
You're doing a lot of API requests with that thing
thanks yo ☠️
import discord
import asyncio
import aiohttp
import time
from discord.ext.commands import Bot, has_permissions, MissingPermissions, Cog
from discord.ext import commands
from random import *
class Test(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def cnbc(self, ctx):
t = randint(180, 600)
old_links = []
with open("old_links.txt", "r", encoding="utf-8") as file:
old_links = file.read().splitlines()
while True:
try:
channel = bot.get_channel(text_channel)
base_url = 'https://www.cnbc.com/world/'
async with aiohttp.ClientSession() as sess:
async with sess.get(base_url, headers={'user-agent': 'Mozilla/5.0'}) as res:
text = await res.text()
soup = bs(text, 'lxml')
title = soup.find("div", attrs={"class":"LatestNews-container"}).a.text.strip()
link = soup.find("div", attrs={"class":"LatestNews-container"}).a['href']
if link not in old_links:
embed=discord.Embed(title=title, url=link)
embed.set_author(name="CNBC")
await channel.send(embed=embed)
old_links.append(link)
with open("old_links.txt", "w", encoding="utf-8") as file:
file.write("\n".join(old_links))
else:
pass
except Exception as e:
await channel.send("❗ CNBC = An error please check ❗")
await asyncio.sleep(t)
async def setup(bot):
await bot.add_cog(Test(bot))
it worked as well before seperate files using cog and other commands are working well with cogs but only crawling is not working without any errors :((
what do you mean "not working", are you getting an error?
You're creating new client sessions and fileio every loop
as in, is the except part triggering?
nope there is no errors but when i write a command on discord, its nothing happen but other commands are working well
only crawling function is not working 😭
remove the try-except, it should give you some idea
ohhh
and maybe add something in the else so you know if it's executing
thank you so much! i will try. but it was working as well before using cog. :((
Are slash or traditional commands better?
Prefix commands are far better in terms of argument parsing
In terms they support arglist, I wouldn't say there are any more advantages regarding argparsing
The main advantage of prefix commands is there can be unlimited amount of them unlike slash commands
I can't really think of anything else
Hello,
Is there away to set permissions in a private channel?
For example like this:
for channel in ctx.guild.channels:
await channel.set_permissions(muted, speak=False, send_messages=False, read_message_history=True, read_messages=True)
how do i use this within my code?
Just edit the embed instead of sending
"You are viewing moderation commands now or smthing"
where would i add into my code depending on what is selected python await edit_message(embed=moderationEmbed)
Just add this line instead of
await interaction.response.send_message(embed=moderationEmbed)
To
await interaction.response.edit_message(embed=...)
Not hard 🗿
Hewo exen 
Hello
What's up xd
Private to whom
I've been sick recently so I didn't come to here often
Oh, hope you will get well soon.
All the channels which don't have everyone role view permission
I'm already fine ty
The bot should have permission to edit the channel then yes
If the bot can't see them it won't be able to edit them neither
im really confused-
!d discord.TextChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this...
Hm...
Show code
ok
class Dropdown(discord.ui.Select):
def __init__(self):
options = [
discord.SelectOption(label='General', description='Provides you with general commands and information about them.', emoji='1️⃣'),
discord.SelectOption(label='Moderation', description='Provides you with moderation commands and information about them.', emoji='2️⃣'),
]
super().__init__(placeholder='Choose what type of help you need below.', min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
await interaction.response.edit_message(embed=...)
class DropdownView(discord.ui.View):
def __init__(self):
super().__init__()
self.add_item(Dropdown())
class Bot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.message_content = True
super().__init__(command_prefix=commands.when_mentioned_or('k!'), intents=intents)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
bot = Bot()
@bot.tree.command(name="help", description="Provides you with the help embed!")
async def _help(interaction):
embed=discord.Embed(title="Help Menu", description="To find the help you're looking for, look below in this embed for whatever you need help with!", color=0xFF5349)
view = DropdownView()
await interaction.response.send_message(embed=embed, view=view)```
class discord.SelectOption(*, label, value=..., description=None, emoji=None, default=False)```
Represents a select menu’s option.
These can be created by users.
New in version 2.0.
value=...
Add some value so you can compare
like if self.values[0]==1or2orn:
#do something
Integer
discord.SelectOption(label='General', value=..., description='Provides you with general commands and information about them.', emoji='1️⃣'),
discord.SelectOption(label='Moderation', value=..., description='Provides you with moderation commands and information about them.', emoji='2️⃣'),```?
Set the value a unique integer bruh
value=1
value=2
If i don't use cog in main.py and enter command in discord it works. But in cog it doesn't work. Other commands in cogs are working. I don't know why only crawling command is not working :(((
For first select option use 1 or whatever for 2nd use 2 or whatever
Should be unique for each options
ok
What's the prob
what else do i need to do?
Do you even know what you're doing
Now just for call back use
if self.values[0]==1:
await interaction.response.edit_message(embed=yourembed)
xd

where in the code do i put the embed
I put all the Discord commands in one Python file(main.py) And i studied about cog today and seperated python files of discord by function to make them easier to manage. However, only the crawl file does not work. There are even no errors. and other commands are working well in cogs.
@shrewd fjord
Traceback (most recent call last):
File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 976, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "C:\Users\LOKESH\Desktop\Lokesh\Pycord\cogs\giveaway.py", line 132, in start
msg = await channel.send(embed=embed, view=view)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\abc.py", line 1622, in send
state.store_view(view, ret.id)
File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\state.py", line 386, in store_view
self._view_store.add_view(view, message_id)
File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 582, in add_view
view._start_listening_from_store(self)
File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 425, in _start_listening_from_store
self.__timeout_expiry = time.monotonic() + self.timeout
~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for +: 'float' and 'Giveaway'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: unsupported operand type(s) for +: 'float' and 'Giveaway'```
i cannot figure out where the error is
hi I need some help to make an invite tracker for my bot
I'm trying to figure out who invited my bot to whatever server they invited it too
so far I was able to get the server name
but not the member who invited the bot
async def on_guild_join(guild):
channel = bot.get_channel(CHANNEL NAME)
invite = await guild.invites()
integrations = await guild.integrations()
message = f'Member {#member name} invited to server: **{guild.name}**'
await channel.send(message)
theres the code so far
I tried using integrations to get the name but it doesn't work
I tried using ctx to get the member name with ctx.guild.id but that doesn't work
Why
It's API limitations
Is there any easier way to do this?
if len(queue) == 1:
embed = discord.Embed(title='1 player is currently in the queue',
description=f'{member.mention} has been added to the queue.',
timestamp=datetime.datetime.now(), color=discord.Color.blue())
else:
embed = discord.Embed(title=f'{len(queue)} players are currently in the queue',
description=f'{member.mention} has been added to the queue.',
timestamp=datetime.datetime.now(), color=discord.Color.blue())```
Do what
embed = discord.Embed(
title=f"{len(queue)} player{'s' if len(queue) > 1 else ''} is currently in the queue",
description=f"{member.mention} has been added to the queue.",
timestamp=datetime.datetime.now(), color=discord.Color.blue()
)
Oh you mean the s
That would add s if the queue len is 1
!e 
cats = [1]
print("Multiple") if len(cats) == 1 else print("Single")
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
Multiple
Just do > at this point
Like this?
title = "1 player is currently in the queue" if len(queue) == 1 else f'{len(queue)} players are currently in the queue'```
how can you use a dictionary from another file and get data from it?
!e ```py
queue = ["player"]
print(f"{len(queue)} player{'s' if len(queue) > 1 else ''} is currently in the queue")
queue = ["player", "player"]
print(f"{len(queue)} player{'s are' if len(queue) > 1 else ' is'} currently in the queue")
@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1 player is currently in the queue
002 | 2 players are currently in the queue
Second one?
?
print(f"{len(queue)} player{'s are' if len(queue) > 1 else ' is'} currently in the queue")```
Nvm
for how long have your discord client been outdated lol
new codeblock colors came like a month or two ago
It's just that I never looked at it
I was really into competitive coding last like 4 months
so I didn't use codeblocks in discord
didnt need it
but some bots have that feature on discord...so its not impossible
Prob audit log
but how did they implement that in their bot?
Wot
its a feature which can be applied in bots
Yes. If you code it.
so...how do you get the name of the member who invited the bot to the server?
I got how to print the server name
its just the member now
There's no such thing, not even audit logs
heres an example for it
by invite tracker
afaik there is no possible way of making your client sub to an event that gives you invite tracking data, iirc bots like invite tracker uses an algorithm to figure out who invited who by storing the user who created the invite and then check if the invite use count went up at the same time a user joined, but it's really inaccurate for larger servers with frequent joins
!d discord.Invite.inviter
The user who created the invite.
And I'm guessing they cache every single invite and have some kind of schedule queue to avoid any minor bugs.
how do they figure out which invite a user joined with though
say in a busy server like this one
with frequent joins, simultaneous joins are possible
!d discord.Invite.uses
How many times the invite has been used.
that's still not a way to figure out which invite a user joined with
The comparing the invite usages before and after the join is just to identify whom invited whom.
yeah, quite inaccurate
Not if you cache every single invite and instead of running it true async have a async schedule que.
or store it all in a database
the events dispatched will not be accurate, so it doesn't matter how you handle it
but that would be really memory consuming
Pretty sure the invite tracker bot isn't 100% accurate either.
ic
fair enough
I don't see the usage in it anyways.
p_message = message.lower() 'hello' = 'hello welcome whatsup'
``` Syntax is a bit off.
p_message = message.lower() 'hello' = 'hello welcome whatsup'
``` this is the problem, what are you trying to do?
no, what is that line supposed to do
still quite vague
that line alone, what are you trying to do with it
seems like you should remove the "hello" = "hello ..." part completely
Have you coded a lot in Python before this? Or have any experience regarding Discord or chatbots?
Chatbots are made using models and by tokenizing certain strings inside a sentence.
Here's an example of how that would look like if you're processing it. json {"intents": [ { "tag": "greetings", "patterns": ["hello", "hey", "hi", "good day", "greetings", "what's up"], "responses": ["Hello!", "Hey!"] }] }
This was a real rough example.
You'd also need to have a trainer for the module and to execute it.
List is longer just copied it.
It's pretty tough to make especially in a bot.
I recommend making it separate first then combine it.
@client.event
async def on_message(message):
if message.author.bot:
return
There are some good videos on youtube for chatbots. I recommend not watching videos that are 1 year or older.
Then learn how to make discord bots as well then later combine the 2 in 1 program.
I recommend having the google filter on < 1 year
This tutorial video makes me wanna make my own and then do it properly.
the worst part is that they don't mention about the stuff that has heen outdated in the title or description, its just post and forget lol
*heen = been
i have a error guys
`import requests
import time
import telegram
Your Telegram bot's API key
API_KEY = '***********'
The chat ID of the Telegram user or group you want to send the price to
CHAT_ID = '********'
The URL for the CoinMarketCap API endpoint for Bitcoin
BTC_PRICE_API_URL = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=BTC&convert=USD'
The header for the CoinMarketCap API request
HEADERS = {
'Accepts': 'application/json',
'X-CMC_Pro_API_Key': '****************',
}
Initialize the Telegram bot
bot = telegram.Bot(token=API_KEY)
Function to get the latest price of Bitcoin
def get_btc_price():
response = requests.get(BTC_PRICE_API_URL, headers=HEADERS)
data = response.json()
btc_price = data['data']['BTC']['quote']['USD']['price']
return btc_price
Function to send the latest price of Bitcoin to Telegram
def send_btc_price_to_telegram():
btc_price = get_btc_price()
message = f'The current price of Bitcoin (BTC) is ${btc_price:.2f}.'
await bot.send_message(chat_id=CHAT_ID, text=message)
Send the price of Bitcoin to Telegram every hour
while True:
send_btc_price_to_telegram()
time.sleep(5)
`
how can i fixe it pls
This is the Discord bots channel please make a post on #1035199133436354600
https://paste.pythondiscord.com/pixeqamebu
await interaction.response.defer()
try:
tim = round(time.time())
if "m" in timestamp:
tim+=int(timestamp.lower().replace("minutes","").replace("minute","").replace("m",""))*60
if "h" in timestamp:
tim+=int(timestamp.lower().replace("hours","").replace("hour","").replace("h",""))*3600
if "d" in timestamp:
tim+=int(timestamp.lower().replace("days","").replace("day","").replace("d",""))*86400
await interaction.followup.send(f"`<t:{tim}:R>`")
except:
await interaction.followup.send(f"Error, please try minutes, hours, or days. For example, `10h`.")
Idk why there is unknown interaction error for the line of defer above. There's nothing that is blocking the code that I can tell... There was nothing running other than this part, it is a slash command I implemented and that was the only command that was used at that moment.
ping if here, thx
you're not making any response?
uh basically defer is a type of response, so in the line await interaction.**response**.defer(), it responds to the interaction. Then, the other followups are basically needed for after a deferred msg is done
How can I use the images from local directory? This isn't working.
thumbnail_url = f'/images/ranked-emblem/{lowered_rank}.png'
embed.set_thumbnail(url=thumbnail_url)```
I want to use images from /images/ranked-emblem/
afaik defer expects a response to finish the interaction, after a proper response you send a followup webhook
yeah
yeah, and you're not doing that
what
so what am i supposed to do
if i do response send msg as a proper response, im pretty sure it will not work
replace followup.send with response.send_message?
have you tried?
are u sure it works with defer?
interaction can only be responded once and yes
yes? defer wants a response?
it should be
trying wont hurt
worst case, we can just dig into it further down and find another solution, but try that first
i have tried yes
and what error did you get
as i said, defer responds to the interaction and yes, its preparing for another response but since it already is responded, the only thing that you can use is followup
this is afaik, I've tried this when I started discord bot stuff and it didnt work
do u get it now?
like what i mean by it has to be followup
yeah, in that case i must've confused it, apologies
alr, unknown interaction can be caused by blocking i heard so idk what is causing this problem if theres nothing blocking its so weird
i see, can you post the full traceback using the followups instead?
How can I use the images from local directory? This isn't working.
thumbnail_url = f'/images/ranked-emblem/{lowered_rank}.png'
embed.set_thumbnail(url=thumbnail_url)```
i cant get it again
it was caused when someone else used it, im not exactly sure what happened
nvm then, if i get it again ill come here and show the traceback
!local-file
Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:
# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")
# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
file = discord.File(f)
When using the file-like object, you have to open it in rb ('read binary') mode. Also, in this case, passing filename to it is not necessary.
Please note that filename must not contain underscores. This is a Discord limitation.
discord.Embed instances have a set_image method which can be used to set an attachment as an image:
embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png") # Filename here must be exactly same as attachment filename.
After this, you can send an embed with an attachment to Discord:
await channel.send(file=file, embed=embed)
This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.
@slate swan But it should only set thumbnail if not Unranked. Do you know how to fix this?
# Add rank emblem to the Embed
rank, *_ = tier_and_rank.partition(" ")
lowered_rank = rank.lower()
if lowered_rank and lowered_rank != 'unranked':
thumbnail_url = f'https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-shared-components/global/default/{lowered_rank}.png'
embed.set_thumbnail(url=thumbnail_url)
# Send the Embed object to the user
await ctx.channel.send(embed=embed)```
As with this code it will not add thumbnail if Unranked.
How do you guys host your bots?
Using uptimerobot or some other websites. Or something completely different like webservers.
What if I don't use repl for bot creation then how should I host it so that it becomes available 24*7
this might help you #discord-bots message
Change
if lowered_rank and lowered_rank != 'unranked':
to
if lowered_rank != 'unranked':
idk why do you have that, that's not making any sense either
Do you know how can I fix the file=file, so that it doesn't trigger it when Unranked?
if lowered_rank and lowered_rank != 'unranked':
file = discord.File(f'/root/images/ranked-emblem/{lowered_rank}.png',
filename="ranked_emblem.png")
embed.set_thumbnail(url="attachment://ranked_emblem")
await ctx.channel.send(file=file, embed=embed)```
you're passing the wrong argument types for discord.file
you have to provide a bytes-like object (use open or preferably aiofiles.open)
!d discord.File
class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:
# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")
# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
file = discord.File(f)
When using the file-like object, you have to open it in rb ('read binary') mode. Also, in this case, passing filename to it is not necessary.
Please note that filename must not contain underscores. This is a Discord limitation.
discord.Embed instances have a set_image method which can be used to set an attachment as an image:
embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png") # Filename here must be exactly same as attachment filename.
After this, you can send an embed with an attachment to Discord:
await channel.send(file=file, embed=embed)
This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.
oh
the docs say something else, my bad
but the docs need to be correct lmao
(nvm I didn't read the whole thing, my bad
guys when i run my discord bot it says logging using static token and gives a long list of errorsw then a runtime error
doesn't help
what is the error?
Could I use this?
await ctx.channel.send(file=file if lowered_rank != 'unranked' else None, embed=embed)```
totally valid, yes
Your code is trying to use intents which haven't been enabled in your app on the discord dev portal
- go to discord developers (https://discord.dev)
- Go to
Applicationsand open the required app - Go to the
BotSection and scroll down - Enable the intents your bot requires and hit
Save - Try to run your code again
@upbeat otter what do you think about this : https://dash.daki.cc
It's a free hosting service
Like heroku
heroku isn't free anymore
and free hosting services aren't really that much reliable nor are they good in their own ways
I can't even access the website without creating an account wtf 💀
Oh
This vedio talks about it : https://m.youtube.com/watch?v=kIvfYWP-nTk
► [NEW] Host Your Discord Bot 24/7 For FREE! - (NOT Heroku)
Ever since Heroku announced they are no longer going to support free services starting November, people who want free hosting already can find an alternative to host their discord bots all for free! in today's video I present you a new discord bot free hosting service with 24/7 uptime,...
i mean, instead of using these bs "free" solutions, just pay for a proper vps
i pay $0.97 per month for mine and i host like 7-8 apps on it, five nines uptime and it's running ubuntu, you have so much more options and flexibility with a vps than that
all of their slots are full atm
shady looking site fr
it says interaction failed when i click on one of the dropdowns but i got no errors
this is my code https://paste.pythondiscord.com/uvubocusog
Send website link
@sick birch How I can get a channel object searching by channel name within a task?
Do you have access to the bot instance from within the task?
believe so yes
How about the guild
discord.utils.get(bot.guild.channels, name="channel") but bot.guild.channels doesn't exist so I don't know how to get it lol
from discord.ext import tasks, commands
class MyCog(commands.Cog):
def __init__(self, bot):
self.index = 0
self.bot = bot
self.printer.start()
def cog_unload(self):
self.printer.cancel()
@tasks.loop(seconds=5.0)
async def printer(self):
print(self.index)
self.index += 1
@printer.before_loop
async def before_printer(self):
print('waiting...')
await self.bot.wait_until_ready()
Wait until the bot is ready before the loop starts
my loop isn't in a cog
anyone?
@sick birch How are you supposed to use tasks? it seems like it's blocking my code for some reason
What is your task doing?
sending an embed
And how are you telling it's blocking?
another on_message function is supposed to delete messages from a certain channel but it stops randomly
I'm using .listen() for the function to delete messages and an on_ready event to start the task
What do you think about uptimerobot and replit. I will get a webserver once my bot is ready.
When you start the task after on_ready but also wait for on_ready inside your task, it deadlocks IIRC
^
ovhcloud
@sick birch How can I make an interactive setup type command? Like you run ,setup and it will prompt you for certain things then wait for you to reply etc
can someone explain how i can use buttons with bot.wait_for ?
!d discord.Client.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
im trying to make a xp bot with a cog but the cog itself doesnt work. if i run the code without the cog it works just fine. no errors or tracebacks
class XPCOG(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print("ready")
@commands.Cog.listener()
async def on_member_join(self, member):
# code here
@commands.Cog.listener()
async def on_message(self, message):
# code here
@commands.Cog.listener()
async def update_data(self, users, user):
# code here
@commands.Cog.listener()
async def level_up(self, users, user, message):
# code here
@commands.command()
async def level(self, ctx, member: discord.Member = None):
# code here
i just started using cogs, so if i have a bad question sorry
Did you add the cog
yeah
how to make my button interact
i watched litterly 20 tutorials
and everyone makes it diffrent
did you make a view first
Don't watch YouTube tutorials
also do you have to do bot.add_cog() in an async thing?
Yes
bro most help but after 20 times diffrent code i am just confused so can someone explain how to use buttons
and give them a function
There's a bunch of example there
https://github.com/Rapptz/discord.py/blob/master/examples/views/counter.py here is a simple one
can someone help with this
class Counter(discord.ui.View):
# Define the actual button
# When pressed, this increments the number displayed until it hits 5.
# When it hits 5, the counter button is disabled and it turns green.
# note: The name of the function does not matter to the library
@discord.ui.button(label='0', style=discord.ButtonStyle.red)
async def count(self, interaction: discord.Interaction, button: discord.ui.Button):
number = int(button.label) if button.label else 0
if number + 1 >= 5:
button.style = discord.ButtonStyle.green
button.disabled = True
button.label = str(number + 1)
# Make sure to update the message with our updated selves
await interaction.response.edit_message(view=self)
@bot.command()
async def counter(ctx: commands.Context):
"""Starts a counter for pressing."""
await ctx.send('Press!', view=Counter())``` i copied it like this in my code and it says no interaction possible
its everytime says it when i try press a button
did you import discord.ui?
yes
it always say this interaction failed
it says interaction failed when i click on one of the dropdowns but i got no errors
im trying to edit the embed depending on which option they choose
this is my code https://paste.pythondiscord.com/uvubocusog
do you use discord.Client or discord.ext.commands.bot
discord.ext.commands.bot this
can you send your entire code? (make sure to blur the token)
Hey @pseudo saffron!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
idk, it seems to work fine
do i need to have the active developer badge to use buttons ?
your previous code is interfering
im not skilled enough, but somewhere before the button your previous code is doing something that doesnt let your button run
if you make a different file and run it there with just the button it will work
i mean that your button would work if your previous code wasnt there
because your previous code is interfering
but how is it interfering i mean i dont use any vars in it that could or running tasks
idk, somehow it is
1 sec i will try just run the code without any other code
thats what i meant
it will work like that
you should be loading your cogs in async_hook
whats async_hook ?
or setup_hook i mean
it says interaction failed when i click on one of the dropdowns but i got no errors
im trying to edit the embed depending on which option they choose
this is my code https://paste.pythondiscord.com/uvubocusog
yo @slate swan it dont even work without any other codes
just with the bot commands
can you post the updated code as it is now?
i just made a clean bot file without any commands
to test if my code is messy

