Hi i need some helo... id go to a help channle but this isnt reallt worthy of it... i have a bot i havent coded on for a few months its set to run all the time bjt theres 2 orher codes the codeer who ill call s foujd some code rhat logs messages well the file it dumps to we vant find where the code for it is... iv looked in all the files i can find on replit for tje bot. And the only other one wjo cpuld of done it is the 3rd codes H idk jow to find rhis code that logs it...
Is there anyway on replit i can see history of edited files and who edited them?
#discord-bots
1 messages · Page 81 of 1
I don't believe so no, one reason to be using source control like Git
Im veru inexperienced with codeing and so is S onlt H could do somthing like this
I canr find any file for the code rhat cuases the logging only where rje messages arw stored
Idk if theres hidden folders i canr access or what
I own tje bot and the replit page file thingu
I really would like some help im having a breakdown over this-
I did not want my bot to be used like rhis
client = commands.Bot(command_prefix="?", intents=discord.Intents.default()) #put your own prefix here
@client.event
async def on_ready():
print("bot online") #will print "bot online" in the console when the bot is online
@client.command()
async def ping(ctx):
print("He did it!")
await ctx.send("pong!") #simple command so that when you type "!ping" the bot will respond with "pong!"
why won't it work when i type ?ping ??? it just doesnt do anything
i think the function name for both the buttons are same? which should be not
which should be not
whats your discord.py version?
let me check that
2.0.0
alright so there were some intents changes. define intents before intents = discord.Intents.default() and then intents.message_content = True then pass in that commands.Bot(..., intents=intents)
message_content also needs to be enabled in the dev portal
Hello everyone, I have a question how to make the bot answer you after you answered his message through the reply item (here is a screenshot, do not pay attention that it is in Russian).
👍
bot or user is missing something
[<Member id=942176793706790962 name='Mihai06' discriminator='5334' bot=False nick=None guild=<Guild id=985256066361225226 name='Neon Development' shard_id=0 chunked=True member_count=8>>, <Member id=975385095609405470 name='Neon Canary' discriminator='3883' bot=True nick=None guild=<Guild id=985256066361225226 name='Neon Development' shard_id=0 chunked=True member_count=8>>]
How can I get a list of only the member ids ? Like ```py
["942176793706790962", "975385095609405470"]
Looks like you can't send a message to the ticket channel
property id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.id "discord.User.id")
how do i send a followup message in discord.py
how do I get everyone on a list? when I type in this code, it only prints the bot.
async def on_message(message):
for x in message.guild.members:
print(x.name)```
You're missing guild members intents
how do i do that
!d discord.Intents.members
Whether guild member related events are enabled.
This corresponds to the following events...
what code do i put? i currently have client = discord.Client(intents = discord.Intents.default())
Yeah default doesn't include member intents
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
alr ill give that a try ty
of an interaction
uhhh
now it gives an error to the line where i run the bot
nvm i got it
oh got it tysm
how would i reply a message by finding a certain word within the message so for instance "Xerp: !8ball" or "this is the !8ball command" if it contains !8ball i want it to reply... with the 8ball message...
@a2m.event
async def on_message(message):#, case_insensitive=True):
ComPrefix = "!"
if message.author == a2m.user:
return
if message.author.guild_permissions.administrator: ----Just ignore this(i know it wont work with what im attempting to do)
if ComPrefix + '8ball' in message.content:
# if ComPrefix + 'happy birthday' in message.content.lower():
options = ["Yes", "No", "yes definitely", "it is decidedly so", "signs point to Yes", "it is certain", "without a doubt",
"most likely", "outlook good", "outlook not so good", "as I see it Yes", "better not tell you now", "cannot predict now",
"MY REPLY IS NO", "you may rely on it", "REPLY hazy try again", "ask again later", "concentrate and ask again",
"don't count on it", "very doubtful", "my sources say no"] # all options
await message.channel.send("The magic 8-ball says %s" %random.choice(options).lower())
how can I make it so that after a person responds to a bot message (via the answer function in discord), the bot sends another message to him (I asked before how to do this, I never received an answer)
i tried to implement it through the if construct, but if it turned out to be implemented, I would not ask it, so here
do you mean that you want to detect !8ball happy birthday
and then reply
yes
i also want it to detect the username if possible
but for general commands for all players id be happy wiht just the !8ball (the happy birthday is commented out)
any particular reason you are using message event instead of .command?
but yeah if it detected multiple words like !8bal shake, or !8ball shake violently (not like id use those commands but as an example)
yes because the messages are streaming from a chat in game that relays the message the discord(this is built into the game itself not part of my bot just using the same token)
so when messages stream from the game it will be like Bot: Xerp: in game chat talk here
so i was using on_message to listen to the in-game chat then relay a message if it finds the command from the in game chat so i can do commands with the bot from within the game
so if someone found some loot and wanted to flip a coin then user could to !flip and they flip a coin... but the discord it would print as "BotName: User: !flip"
so if User: wasnt there it would be fine.. so didnt know how to make it find the word then reply
Sorry im trying to explain the best I can
you count take in message.content, see if message.content.startswith(‘!8ball’) and if so just separate the string or wtv you need to do with it and get the rest of the message // might be an easier way but i’m on phone atm
it would never start with the command though... it would start with <usernamehere>: !8ball
The * argument means that every argument after it is keyword-only, meaning you need to specify it like reason=.... The / means that every argument before it is positional only, the opposite of *, where you CANNOT specify it like until=....
i mean if it’s going to be a consistent <username>:something you should still be able to separate everything to what you need
Positional only
await the coroutine
« stop » function is not awaited on my code ?
In your if name main boilerplate, i'd assume
Although the error does tell you exactly
I need to await the stop func in the if statement ?
I was convinced the error was on the func
Define this variable intents=discord.Intents.default() and pass on the commands.Bot args this : intents = intents
thanks
Hi, could someone help me out with this, I'm trying to host my bot on my rasp (kali)
ModuleNotFoundError: No module named 'httpx'
PS C:\Users\dynam\Downloads\boost-bot-main>```
how can i check if my bot has admin prms in a server?
is it possible to leave servers my bot is in
or make invites for me to join them with the discord id?
how would i go about sending a discord msg without ctx? i presume i would need guild/channel, but i honestly have never manually wired it all together. the reason i cant use ctx is that im using a tasks.loop to get the func to be called at a set time; its not being called by a msg being sent
your bot instance would be how you'd retrieve the channel you want to send to
there's several ways to do it but id say these are the normal approaches, assuming you have a specific guild/channel ID:
Client.get_channel(cid)to get a channel by id from cache (looks in all guilds)Client.get_guild(gid)+Guild.get_channel(gid)to get a channel from a guild by cache (constant time lookup)Client.get_partial_messageable(cid)to get a fake channel suitable for sending messages (no cache required)
for methods 1 and 2 you'd want to make sure your bot is ready before the loop starts, otherwise the bot wont have loaded all channels into the cache: py @my_function.before_loop async def before_my_function(): await bot.wait_until_ready()
i can use bot.get_channel too right
yeah Bot inherits the same get_channel method from Client
can you show the code related to your loop?
server that has the bot in it ofc
@tasks.loop(seconds=1)
async def call():
channel = bot.get_channel(624577501590454274)
print(channel)
await channel.send('hello')
epoch_num = 1662859900
if str(epoch_num) in str(time.time()):
the print/hello parts r for testing
this point likely matters then
ohh
also a 1 second send loop is pretty fast
well, i need a way to read epoch; i spose i could take a couple digits off if idc bout it being specific
ive had loads of trouble getting an easy to use timer system, so i just went with this one
but yeah it is
that worked! cheers
just added the wait for into the same func
@tasks.loop(seconds=1)
async def call():
await bot.wait_until_ready()
channel = bot.get_channel(624577501590454274)
print(channel)
await channel.send('hello')
guys, i have a popular verified bot where it's in more than 5k servers, but i was off for sometime, and now none command work, even the $utc to check the UTC time, it don't give me any error on the terminal, someone know something that changed these 2 last years that i should know?
the utc command is just:
@bot.command()
async def utc(ctx):
await ctx.send(f"> {str(dt.datetime.utcnow().time())[:8]} utc")
and dont work anymore
Bad news for you
None of your commands will work and you'll need to do a full rehaul to slash commands
Discord most certainly won't grant you message content intents for regular commands
do u have a tutorial link about it?
On slash commands?
ye
Tutorials are bad, see the examples in the github repo
how do i ping a role? ie whats the correct syntax
Discord Developer Portal
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
does anyone know any good free alternatives to heroku for discord bot hosting
"good free" is an oxymoron
Either it's good but costs money or it's free and low-quality
my bank account is lower quality
`import discord
import os
import random
from dotenv import load_dotenv
load_dotenv()
client = discord.Bot()
token = os.getenv('TOKEN')
@client.event
async def on_ready():
print("Logged in as a bot {0.user}".format(client))
@client.event
async def on_message(message):
username = str(message.author).split("#")[0]
channel = str(message.channel.name)
user_message = str(message.content)
print(f'Message {user_message} by {username} on {channel}')
if message.author == client.user:
return
if channel == "random":
if user_message.lower() == "hello" or user_message.lower() == "hi":
await message.channel.send(f'Hello {username}')
return
elif user_message.lower() == "bye":
await message.channel.send(f'Bye {username}')
elif user_message.lower() == "...":
jokes = ["..."]
await message.channel.send(random.choice(jokes))
client.run(token)`
I got this error when running the code I learned from youtube
How do I fix this?
is this discord.py or pycord?
Also is this lucas's video?
Umm no
Looks like it
Free code camp and other
It's terrible, to be honest
:D
Why do yall even like watching code videos
I didnt learn python to this
I'd suggest trying to learn it on your own using the documentation & examples instead
These tutorials are... not the best, to say the least
ik
Imho they take too long time to watch
I also don't see the appeal of being told which keys to press
I'd rather problem solve and come up with ideas on my own
Isn't it better to quickly read some tutorial article or guide
Yeah definately the basic video I got from a community has 104 and i got like 65 now
104 what
How can I push the user another selection menu in interaction.response?
Where is the # in this tuple
What do you want to get from it
!e py tup = (1234,) print(tup[0])
?
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
1234
use the edit_original_message of the Interaction object and send a new view using the view kwarg
that wasn't even a channel related question
That's 1 element tuple why can't you
if you are talking ab me i just came here because it was for a userid x)
nah im just drunk and for some reason wanted to splice it really badly
doesn't matter. anyways not gonna argue
appreciate ya
<3 my b cutie
That's like "hey guys how do I make an AI chatbot, I wanna put it into a discord bot" this would be more #data-science-and-ml related question
yeah I find that people tend to come here with any problem that they encounter while making a discord bot with the justification that their problem is "related to a discord bot"
honestly though thats what i see in here half the time
You can ask simple questions in #python-discussion, that's common thing
Though if a problem is quick and simple enough we'll just answer it and send them on their way
honestly speaking, a good three quarters of the issues are related to python while making a discord bot
it was an autopilot question because i knew it was entry level simple
Man you don't really need to make excuses, we are just giving an advice
or more like it's a general issue, isn't directed towards anyone
class MyHelp(commands.HelpCommand):
async def send_bot_help(self, mapping):
embed = discord.Embed(title="PLAYGROUND Bot Help")
for cog, commands in mapping.items():
command_signatures = [self.get_command_signature(c) for c in commands]
if command_signatures:
cog_name = getattr(cog, "qualified_name", "No Category")
embed.add_field(name=cog_name, value="\n".join(command_signatures), inline=False)
channel = self.get_destination()
await channel.send(embed=embed)
client.help_command = MyHelp()```
how can i make this
perm restricted
only admins can use\
oh nah i’m not taking it personally just sayin
Do you want all commands of your bot to be available to admins only or just this help command?
only help
Well it has add_check ig you can use it in init, not sure if you can decorate this class with @check, or you could put some condition to the function itself
!d discord.ext.commands.HelpCommand.add_check
add_check(func, /)```
Adds a check to the help command.
New in version 1.4.
Changed in version 2.0: `func` parameter is now positional-only.
See also
The [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") decorator
class MyHelp(commands.HelpCommand):
@commands.has_permissions(manage_messages=True)
async def send_bot_help(self, mapping):
embed = discord.Embed(title="PLAYGROUND Bot Help")
for cog, commands in mapping.items():
command_signatures = [self.get_command_signature(c) for c in commands]
if command_signatures:
cog_name = getattr(cog, "qualified_name", "No Category")
embed.add_field(name=cog_name, value="\n".join(command_signatures), inline=False)
channel = self.get_destination()
await channel.send(embed=embed)
client.help_command = MyHelp()```
like this
How to let discord bot call another command when certain condition(s) are met?
if statement
if-else
Yes, but what about call command?
if condition=true, call command...
Depends on where the command is stored at, if it's just a function in the same cog or the same module, you can just call it like a normal function ie await command(ctx, arg1, arg2), if it's in another cog it's better to use invoke method of Command object
I forgor
!d discord.ext.commands.Command
class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the decorator or functional interface.
@vale wing any idea /
!d discord.ext.commands.Context.invoke
await invoke(command, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Calls a command with the arguments given.
This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.
Note
This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.
You must take care in passing the proper arguments when using this function...
What idea, I told you absolutely different thing
What is the best module to make a simple economy system?
NewcomerEmbed = disnake.Embed(title="...",
description="",
colour=disnake.Colour.random(),
url="Link Here")
NewcomerEmbed.add_field(name="...",
value="""...""",
inline=True)
NewcomerEmbed.add_field(name="...",
value="""...""",
inline=True)
NewcomerEmbed.add_field(name="**...**",
value="""...""")
I'm doing the inline part correctly, right? I want the 1st two Fields to be inlined but when It sends, the inlined fields are not working. What am I doing wrong here?
Here is what the embed sends me. Wait. Let me edit the dots for more context lol. A tad confusing as is
Anyone here? lol. I just need t fix this single inline problem and I'll be good
Ah, nvm lol. It seems that Inline is set to True as default
whats wrong here??
@starboard.command()
@checks.not_blacklisted()
async def set(self, context: Context, channel: discord.TextChannel) -> None:
async with self.client.pool.acquire() as connection:
async with connection.cursor() as cursor:
await cursor.execute(f"SELECT * FROM starboard WHERE guild_id ={context.guild.id}")
channelData= await cursor.fetchone()
if channelData:
channelData = channelData[0]
if channelData ==channel.id:
return await context.send("This channel is already the starboard channel.")
await cursor.execute(f"UPDATE starboard SET channel_id = {channel.id} WHERE guild_id = {context.guild.id}")
await context.send(f"Starboard channel set to {channel.mention}")
else:
await cursor.execute(f"INSERT INTO starboard (guild_id, channel_id , starLimit) VALUES ({context.guild.id}, {channel.id} , 5)")
await context.send(f"Starboard channel set to {channel.mention}")
await cursor.close()
discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'set' raised an exception: AttributeError: 'Bot' object has no attribute 'pool'
async def give(ctx, member:discord.Member, amount):
...
await open_account(ctx.author)```
how should I put a check that the "amount" is a integer or not
amount: int
Have you read the error message?
you didn't set an attribute in your bot called, pool... So, you can't use it, first do that
You probably missed copying a part of code from that YouTube tutorial you were watching
How to get a Random user from the list of participants in your server?
!d random.choice
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
so I have a write the name of all paricipants in a list?
property members```
A list of members that belong to this guild.
hmmmm
This returns a list of all members
So if u have a guild object
Just do random.choice(guild.members)
@checks.not_blacklisted()
async def set(self, context: Context, channel: discord.TextChannel) -> None:
connection = sqlite3.connect("database/database.db")
async with connection.cursor() as cursor:
await cursor.execute(f"SELECT * FROM starboard WHERE guild_id ={context.guild.id}")
channelData= await cursor.fetchone()
if channelData:
channelData = channelData[0]
if channelData ==channel.id:
return await context.send("This channel is already the starboard channel.")
await cursor.execute(f"UPDATE starboard SET channel_id = {channel.id} WHERE guild_id = {context.guild.id}")
await context.send(f"Starboard channel set to {channel.mention}")
else:
await cursor.execute(f"INSERT INTO starboard (guild_id, channel_id , starLimit) VALUES ({context.guild.id}, {channel.id} , 5)")
await context.send(f"Starboard channel set to {channel.mention}")
await cursor.close()```
am new to sql
I forgot...
how may i connect and use it?
This is how to define a guild object right?
a = client.get_guild(id)
dfiscord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'set' raised an exception: AttributeError: __aenter__
Yes, or if ur in a command can do ctx.guild or interaction.guild
Hi
Hi
How to get next msg in dc py
!d discord.ext.commands.Bot.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.10)"). 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.10)") 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.10)") 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**...
Ok and how to get it's content like if it's embed
Seperate event
!d discord.Message
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the message’s hash.
Okok thanks
@bot.command() async def test(ctx, arg): await ctx.send(arg)
The 'test' cmd does not exist How do I fix this?
did you forgot to save the python file?
show error my friend
Name the cmd lol
its test :/
That's the function's name
i know but if there is no name
the function name will be the name
the function name becomes the command name
First i've heard of that
ya
lol. Anyways, I've also got a qustion of my own (Regarding channel perms)
If I enable the Use External Emoji/Stickers for @ everyone but I restrict it using X role, would the users with the X role be unable to use External Emojis/Stickers unless they have a higher role that has the Use External Emojis/Sticker perms?
My bot's emojis are suddenly messed up due to this problem so I'm tryna fix it without really making a mess out of my server's perms
how to arrange my json data in separate line?
oop I didn't ment to tag you
soory
how to arrange my json data in separate line????
how are you dumping it
you're getting Forbidden for sending a message from what i can see
I would recommend pasting the code and error instead of sending SS, it's easier to debug
if it's too long you can use https://paste.pythondiscord.com
json dump has an indent kwarg use that
!d json.dump
json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* as a JSON formatted stream to *fp* (a `.write()`-supporting [file-like object](https://docs.python.org/3/glossary.html#term-file-like-object)) using this [conversion table](https://docs.python.org/3/library/json.html#py-to-json-table).
If *skipkeys* is true (default: `False`), then dict keys that are not of a basic type ([`str`](https://docs.python.org/3/library/stdtypes.html#str "str"), [`int`](https://docs.python.org/3/library/functions.html#int "int"), [`float`](https://docs.python.org/3/library/functions.html#float "float"), [`bool`](https://docs.python.org/3/library/functions.html#bool "bool"), `None`) will be skipped instead of raising a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError").
The [`json`](https://docs.python.org/3/library/json.html#module-json "json: Encode and decode the JSON format.") module always produces [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") objects, not [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. Therefore, `fp.write()` must support [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") input.
If *ensure\_ascii* is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If *ensure\_ascii* is false, these characters will be output as-is.
Thanks buddy 😊
from discord.utils import get
@bot.command(pass_context=True)
async def purge_members(ctx):
for member in ctx.message.server.members:
if not get(member.roles, name='calls'):
else not get(members.roles, name='notifications'):
await bot.kick(member)```
Not discord bot related xD
it is discord.py
is this correct?
idk
its my discord bot script
idk why i am getting error
bot not coming online
send full script
@client.event
async def on_message(message):
channel_final = client.get_channel(942848242616516638)
channel_final_mi = client.get_channel(640107632690200587)# channel to ping message if approved
button1 = Button(label="Approve!",style=discord.ButtonStyle.green)
button3 = Button(label="Disapprove - No Mute", style=discord.ButtonStyle.blurple)
button2 = Button(label="Disapprove!",style=discord.ButtonStyle.red)
view = View()
view.add_item(button1)
view.add_item(button3)
view.add_item(button2)
message_channel = message.channel.id
user_id = message.author.id
channel_sent_in = message.channel
# Check if message has content
if message.content is not None and message_channel == 1017792577740734536 or message_channel == 1018468004121542716: #channel its monitoring
# Add message content to list
msg_list.append(message.content)
img_list.append(message.attachments)
await message.delete()
print(msg_list)
comhelper = '<@&889878315089932328>'
staff = '<@&810238562053914695>'
admin = '<@&811310504471035935>'
channel = client.get_channel(1017118446284177419) # channel where checked if post is good
embed = discord.Embed(title=f'Message detected in #{channel_sent_in}', color = 10181046)
embed.add_field(name='Message: ', value=f'{message.content}')
embed.add_field(name='User: ', value=f'{message.author}')
embed.set_footer(text=f'Provided by Donks#1048 • {current_time}')
await channel.send(f"Here: {comhelper + staff + admin}")
await channel.send(embed=embed, view=view)``` with this code here, how would i also foward and image if it is sent
Error:
AttributeError: 'Intents' object has no attribute 'member'```
Code:
```intents = discord.Intents.default()
intents.member = True```
discord.app_commands.errors.CommandInvokeError: Command 'set' raised an exception: AttributeError: __aenter__
@starboard.command()
@checks.not_blacklisted()
async def set(self, context: Context, channel: discord.TextChannel) -> None:
async with self.client.db.cursor() as cursor:
await cursor.execute(f"SELECT * FROM starboard WHERE guild_id ={context.guild.id}")
channelData= await cursor.fetchone()
if channelData:
channelData = channelData[0]
if channelData ==channel.id:
return await context.send("This channel is already the starboard channel.")
await cursor.execute(f"UPDATE starboard SET channel_id = {channel.id} WHERE guild_id = {context.guild.id}")
await context.send(f"Starboard channel set to {channel.mention}")
else:
await cursor.execute(f"INSERT INTO starboard (guild_id, channel_id , starLimit) VALUES ({context.guild.id}, {channel.id} , 5)")
await context.send(f"Starboard channel set to {channel.mention}")
await cursor.close()```
members
Check the docs when you get AttributeError since the valid attributes are listed there
right, thank you
alr, thnx
What does client.db.cursor() return
return sqlite3.connect("database/database.db")
client.db = connect_db()
An sqlite3 cursor definitely doesn't have aenter
You should use some async library like aiosqlite
I'm kinda brain dead or smth but, how do I get a list of all the components inside a view
!d discord.ui.View.children
property children```
The list of children attached to this view.
slow bot
How do i copy images from channels?
As atm got message.content grabbing text, but cant grab images
!d discord.Message.attachments
A list of attachments given to a message. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
@paper sluiceRYuga
How would i go about fowarding their image tho, as seems u can only get info abt image
if you wannna send it to a channel in discord, you can simply access the url (url property) and send the url and discord'll render it for you
from event import Event
intents = discord.Intents.default()
intents.members = True
prefix = ".a"
bot = commands.Bot(command_prefix=prefix, help_command=None, intents=intents)
token = "the token"
bot.add_cog(Event(bot))
@bot.event
async def on_ready():
print("The Bot is Online")
bot.run(token)```
event.py:
```py
import random
import discord
from discord.ext import commands
import sqlite3
import asyncio
import aiosqlite
class Event(commands.Cog):
def __init__(self,bot):
self.bot = bot
@commands.Cog.listener()
async def setup_hook(self):
db = sqlite3.connect("bal.sqlite")
cursor = db.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS bal (
user_id INTEGER, cash INTEGER, crystals INTEGER, weapon_shards INTEGER, enhancing_stones INTEGER, event_pearls INTEGER, merging_stones INTEGER, fusion_earring INTEGER
)''')
print("Bot is Online")
@commands.Cog.listener()
async def on_message(self, message):
if message.author.bot:
return
user = message.author
db = sqlite3.connect("bal.sqlite")
cb = db.cursor()
cb.execute(f"SELECT user_id FROM bal WHERE user_id = {user.id}")
result = cb.fetchone()
if result is None:
sql = ("INSERT INTO bal(user_id, cash, crystals, event_pearls, weapon_shards, fusion_earring, merging_stones, enhancing_stones) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
val = (user.id, 0, 0, 0, 0, 0, 0, 0, 0)
cb.execute(sql, val)
db.commit()
cb.close()
db.close()```
Not adding the value, nor creating the table
yea i did it now thanks 🙂
You shouldn't connect everytime, only make one connection and use it
And use aiosqlite, not sqlite3
I think w/sqlite3 there is a need to connect everytime
k, but on Discord.py everyone was telling me this is how I should do, and should use sqlite3
same vroo
so, what did u do?
btw OP pfp, Sukuna
No, not at all
xd
sqlite3 isn't async. You should use aiosqlite with a discord bot
!pypi aiosqlite
lmao, someone else said that there isn't a need to connect everytime, but then another person said ...
does anyone have link to that discord bot which was written in 1 line?
thnx 🙂
?
discord bot in just 1 line?
yes
must have been hard af
not really
oh
std = type("std", (object, ), {"cout": type("cout", (object, ), {"__lshift__": lambda self, other: print(other)})()})()
std.cout << "x"```
for discord aiosqlite is better than sqlite ???
(lambda run, *args: run(discord.Client(), *args))((lambda client, *args: [func(client) for func in args]),(lambda client: setattr(client, '__await', client.loop.create_task)),(lambda client: setattr(client, '__commands', {'ping': (lambda message: client.__await(message.channel.send('pong'))), 'whoami': (lambda message: client.__await(message.channel.send('You are %s' %(message.author)))), 'help': (lambda message: client.__await(message.channel.send('\n{0}'.format('\n'.join(name for name in client.__commands)))))})), (lambda c: [setattr(c, key, value) for key, value in {'on_ready': asyncio.coroutine((lambda: print('Logged in as\n%s\n%s\n------' %(c.user.name, c.user.id)))), 'on_connect': asyncio.coroutine(lambda: print('Connected!')), 'on_error': asyncio.coroutine(lambda ctx, error: c.__await(ctx.channel.send(error))), 'on_message': asyncio.coroutine((lambda m: ((c.__commands[m.content[2:]](m), c.on_message)[1] if m.content.startswith('!!') else c.on_message)))}.items()]), (lambda c: [print('Running...'), c.run(token)]))
print('Logged in as\n%s\n%s\n------' %(c.user.name, c.user.id)) 💀
thank you, that's the one i was looking for
😳
cool discord bot
attachment = message.attachments[0].url
IndexError: list index out of range``` how to fix this error?
cause if the user sends text without image, bot break
You can check if the message contains attachment(s) or not
How to do that 🙂
Simply using if statement, example:
if not message.attachments:
return
Return if message has no attachments
still getting this error py attachment = message.attachments[0] IndexError: list index out of range
Did you check if the message has attachments before trying to get it?
Yes
if message.content is not None and not message.attachments and message_channel == 1017792577740734536 or message_channel == 1018468004121542716: #channel its monitoring
# Add message content to list
msg_list.append(message.content)
attachment = message.attachments[0].url
await message.delete()```
That error was raised because the index you're trying to get an element from doesn't exist
How would i fix? 🙂
Uh
First is the not message.attachments will be True if the message has no attachments
So remove the not from it
Done 🙂
Guys i want to make a utilis library for discord.py
What type of library should i make?
And
!or
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
Hey @rain monolith!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Basically, in your code, if the message_channel is 1018468004121542716, it'll bypass the other checks.
if message.content is not None and not message.attachments and message_channel == 1017792577740734536 or message_channel == 1018468004121542716
Ahhhh I see
I wrote a bot but it doesn't work in Discord. When could I have made a mistake?
doesn't online
So fix it by checking if the message_channel is in a list of the IDs instead.
if message.content and message.attachments and message_channel in [1017792577740734536, 1018468004121542716]
and then add this in? if not message.attachments: return
You can use the code above because I've already fixed it for you, but you can still separate it if it looks messy.
Ahh thank you v much
It now seems to not be going through the rest of the code?
await message.delete()
print(msg_list)
comhelper = '<@&889878315089932328>'
staff = '<@&810238562053914695>'
admin = '<@&811310504471035935>'
channel = client.get_channel(1017118446284177419) # channel where checked if post is good
embed = discord.Embed(title=f'Message detected in #{channel_sent_in}', color = 10181046)
embed.add_field(name='Message: ', value=f'{message.content}')
embed.add_field(name='User: ', value=f'{message.author}')
embed.set_image(url= attachment)
embed.set_footer(text=f'Provided by Donks#1048 • {current_time}')
await channel.send(f"Here: {comhelper + staff + admin}")
await channel.send(embed=embed, view=view)```
it's faster to compare with immutables than a mutable
could have used a tuple for speed
error what
How would do this?
cant help, dunno what issue youre facing
getting an error if there isnt an image in the users messag
and was wondering how to still take in there message even if they dont send an image
what do you want to do if there is no image
just carry on with rest of code
so you want to grab only one attachment from the message and if there is none, you wanna carry on with executing other functions, right?
does anyne know why this is happening
yes 🙂
attachment = message.attachments[0].attachments if message.attachments else None
this will grab the first image as an Attachment object from the message else it'll be set to None if there is no image in the message
👍
yes you got ratelimited
do kill 1 in the shell
uh
oh ty
how wld i now make it so it wnt do this py embed.set_image(url= attachment) if no image
as it gets stuck in a loop to send the embed
if message.content is not None and message.attachments and message_channel in 1017792577740734536 or 1018468004121542716: # Add message content to list
msg_list.append(message.content)
attachment = message.attachments[0].attachments if message.attachments else None
await message.delete()
print(msg_list)
comhelper = '<@&889878315089932328>'
staff = '<@&810238562053914695>'
admin = '<@&811310504471035935>'
channel = client.get_channel(1017118446284177419) # channel where checked if post is good
embed = discord.Embed(title=f'Message detected in #{channel_sent_in}', color = 10181046)
embed.add_field(name='Message: ', value=f'{message.content}')
embed.add_field(name='User: ', value=f'{message.author}')
embed.set_image(url= attachment)
embed.set_footer(text=f'Provided by Donks#1048 • {current_time}')
await channel.send(f"Here: {comhelper + staff + admin}")
await channel.send(embed=embed, view=view)```
Well
Uh
The first thing is that you're using or in the wrong way
How come 🙂
!or
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
for some reason when I run this code, nothing happens, but when I try using something like on_message it works
from discord.ext import commands
intents = discord.Intents.default()
client = commands.Bot(command_prefix="!", intents=intents)
@client.command()
async def test(ctx):
await ctx.send("hi")
print("ok")
client.run(token)```
You have to enable intents.message_content for it to work
intents = discord.Intents.default()
intents.message_content = True
...
how would i now fix the issue of the skipping the embed if attactment is none
Uh
Just check if it's not none before setting it
if not attachment:
embed.set_image(url="attachment://preview.png")
ah thank you
also py if message.content is not None and message.attachments and message_channel in [1017792577740734536, 1018468004121542716]:
Seems to not be picking up messages in the channels
Yes 🙂
import discord
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
guild = await client.fetch_guild(768888081121542245)
print(guild.member_count)
why is the Output None?
I have enabled the GUILD_MEMBERS intent in the Developer Portal
embed.set_image(url=message.attachments[0].url if message.attachments else None)
easy peasy
it's erroring in the
if result == None:
...
category.id #category is None as it wasn't passed during command invocation
Why aren't you using subcommands
how can I check that the one who is clicking the button executed the command?
is it possible to make the bot give a specific role?
yes
like, when player have x give em y role
yes
how hard it will be for someone who has never code any discord bot?
But i have already build a bot with .add .remove .... and other commands, of virtual points
Try it out, if you know python basics it won't be hard
how to check with "await_for" if a person has replied to a message?
who suddenly did not understand where the "reply" item is right-click on the message and there will be an answer
wait for "message"
Trying to wait for a message after command was called?
@bot.command()
async def command(ctx):
await ctx.send("Type: `hello`")
def check(m):
return m.content == 'hello' and m.channel.id == ctx.channel.id
try: # wait_for will return Message when check function returns True
msg = await bot.wait_for('message', check=check, timeout=10)
except asyncio.TimeoutError: # wait_for raised TimeoutError after 10 seconds
await ctx.send("10 seconds has passed, timeout.")
else:
await ctx.send(f'Hello `{msg.author}`!')
to be honest, I don't quite understand
I need something I just wanted a person to click on the bot's message and respond through the "reply" item
A time will come... when that command will also stop removing ratelimits
still get this py attachment = message.attachments[0].attachment if message.attachments else None AttributeError: 'Attachment' object has no attribute 'attachment'
guys
what path do i use if i put a json file inside another folder ?
is this the close button
ok
ok
what do the other buttons do ?
and do they work
hmm ok
now if only an image, it wnt work
how to fix?
interaction.message.content
IndexError: list index out of range```
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
emoji = payload.emoji
guild = self.client.get_guild(payload.guild_id)
channel = self.client.get_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)
if emoji.name == "⭐":
cursor = self.client.db.cursor()
cursor.execute(f"SELECT * FROM starboard WHERE guild_id ={guild.id}")
starData= cursor.fetchone()
if starData:
starLimit = starData[2]
starboardChannel = self.client.get_channel(starData[1])
if starboardChannel is None:
return
else:
if message.channel == starboardChannel:
return
else:
if message.author == self.client.user:
return
else:
if message.author == guild.me:
return
else:
if message.author.bot:
return
else:
if message.author == payload.member:
return
else:
if message.reactions[0].count >= starLimit:
async for message in starboardChannel.history(limit=100):
if message.embeds:
if message.embeds[0].footer.text == f"Message ID: {message.id}":
await message.embeds[0].edit(description=f"**`⭐`{message.reactions[0].count}**")
else:
embed = discord.Embed(title=f"⭐ {message.reactions[0].count} ", description=f"[Jump to message!]({message.jump_url})", color=0x03befc)
embed.add_field(name="Message Content", value=message.content, inline=False)
embed.set_footer(text=f"Message ID: {message.id}")
embed.set_author(name=message.author.name, icon_url=message.author.avatar)
embed.timestamp = message.created_at
if message.attachments:
embed.set_image(url=message.attachments[0])
await starboardChannel.send(embed=embed)
cursor.close()```
my code
if the index is out of range for reactions then the message probably has no reactions right
it has
can someone explain this error
2022-09-11T16:13:07.874295+00:00 app[worker.1]: Traceback (most recent call last):
2022-09-11T16:13:07.874308+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/disnake/ext/commands/interaction_bot_base.py", line 1262, in process_application_commands
2022-09-11T16:13:07.874308+00:00 app[worker.1]: await app_command.invoke(interaction)
2022-09-11T16:13:07.874310+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/disnake/ext/commands/base_core.py", line 415, in invoke
2022-09-11T16:13:07.874311+00:00 app[worker.1]: raise CommandInvokeError(exc) from exc
2022-09-11T16:13:07.874325+00:00 app[worker.1]: disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
2022-09-11T16:13:07.874325+00:00 app[worker.1]: In data.components.0.components.0.label: This field is required```
one of your components doesn't have a label... in your first action row in the first component
label is name on the button, right?
yes
are you fetching an emoji to put in it?
yes
could be that the emoji is not fetching properly and you're trying to do emoji=None
you can use just an emoji
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
emoji = payload.emoji
guild = self.client.get_guild(payload.guild_id)
channel = self.client.get_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)
if emoji.name == ":star:":
cursor = self.client.db.cursor()
cursor.execute(f"SELECT * FROM starboard WHERE guild_id ={guild.id}")
starData= cursor.fetchone()
if starData:
starLimit = starData[2]
starboardChannel = self.client.get_channel(starData[1])
if starboardChannel is None:
return
else:
if message.channel == starboardChannel:
return
else:
if message.author == self.client.user:
return
else:
if message.author == guild.me:
return
else:
if message.author.bot:
return
else:
if message.author == payload.member:
return
else:
if message.reactions[0].count >= starLimit:
async for message in starboardChannel.history(limit=100):
if message.embeds:
if message.embeds[0].footer.text == f"Message ID: {message.id}":
await message.embeds[0].edit(description=f"**`⭐`{message.reactions[0].count}**")
else:
embed = discord.Embed(title=f":star: {message.reactions[0].count} ", description=f"[Jump to message!]({message.jump_url})", color=0x03befc)
embed.add_field(name="Message Content", value=message.content, inline=False)
embed.set_footer(text=f"Message ID: {message.id}")
embed.set_author(name=message.author.name, icon_url=message.author.avatar)
embed.timestamp = message.created_at
if message.attachments:
embed.set_image(url=message.attachments[0])
await starboardChannel.send(embed=embed)
cursor.close()```
is your bot a copy of starboard?
i making this for my starboard command
if starboardChannel is None:
return
else:
if message.channel == starboardChannel:
return
else:
if message.author == self.client.user:
return
else:
if message.author == guild.me:
return
else:
if message.author.bot:
return
else:
if message.author == payload.member:
return```
dude
and i want that if the messsage reaction get updated
then update the starboard channel message
yes it printed None
what??
but that emoji exists
if (
starboardChannel is None
or message.channel == starboardChannel
or message.author in (self.client.user, guild.me, payload.member)
or message.author.bot
):
return
Fricking genius
hold on can make it better
How are you getting it
why is it printing none
bot.get_emoji(id)
What are your intents
intents = disnake.Intents.default()
intents.presences = True
intents.members = True
intents.message_content = True
Just fyi you can use disnake.Intents.all() without need to enable those 3
#ping slash command
@nextcord.slash_command(name='ping',description='Check the bot\'s ping!', guild_ids=[702824491667161160])
async def ping(interaction:Interaction):
embed=nextcord.Embed(title='Bot Ping')
embed.add_field(name='My API latency is: ', value= f'{round(self.bot.latency * 1000)}ms')
embed.set_footer(text=f'Ping requested by {interaction.user}', icon_url=interaction.user.display_url)
await interaction.response.send_message(embed=embed)
```how do i fix this error?
sure
but what about that emoji

As for emoji, could you show how exactly you get it
Mhm
I remember there was a problem recently
Not sure if it's about intents but hold on a sec here
😨
yeah i had an issue with emojis recently, trying to remember how i fixed it
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
emoji = payload.emoji
guild = self.client.get_guild(payload.guild_id)
channel = self.client.get_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)
if emoji.name == "⭐":
cursor = self.client.db.cursor()
cursor.execute(f"SELECT * FROM starboard WHERE guild_id ={guild.id}")
starData= cursor.fetchone()
if starData:
starLimit = starData[2]
starboardChannel = self.client.get_channel(starData[1])
if (starboardChannel is None or message.channel == starboardChannel or message.author in (self.client.user, guild.me, payload.member)or message.author.bot ):
return
if message.reactions[0].count >= starLimit:
async for message in starboardChannel.history(limit=100):
if message.embeds:
if message.embeds[0].footer.text == f"Message ID: {message.id}":
print("Message already in starboard.")
else:
if message.reactions[0].count >= starLimit:
embed = discord.Embed(title=f"⭐ {message.reactions[0].count} ", description=f"[Jump to message!]({message.jump_url})", color=0x03befc)
embed.add_field(name="Message Content", value=message.content, inline=False)
embed.set_footer(text=f"Message ID: {message.id}")
embed.set_author(name=message.author.name, icon_url=message.author.avatar)
embed.timestamp = message.created_at
if message.attachments:
embed.set_image(url=message.attachments[0])
await starboardChannel.send(embed=embed)
cursor.close()
?
please use pastebin dude
Error
IndexError: list index out of range```
@dull terrace
@honest shoal try this
intents = disnake.Intents.all()
print(intents.value & 1 << 3 == 1 << 3)```
print(message.reactions)
if it's None then there might be a permissions problem idk
what does it print
what attribute is needed for the bot to answer you? (I tried reply doesn't work)
What library and what command (slash/prefix)
2
did you print message.reactions.count?
nextcord, slash
yes
this is example
!d nextcord.Interaction.send idk
await send(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, delete_after=None, allowed_mentions=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This is a shorthand function for helping in sending messages in response to an interaction. If the interaction has not been responded to, [`InteractionResponse.send_message()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.InteractionResponse.send_message "nextcord.InteractionResponse.send_message") is used. If the response [`is_done()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.InteractionResponse.is_done "nextcord.InteractionResponse.is_done") then the message is sent via [`Interaction.followup`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Interaction.followup "nextcord.Interaction.followup") using [`Webhook.send`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Webhook.send "nextcord.Webhook.send") instead.
print message.reactions
True
Ok then it's not intents issue
[<Reaction emoji='⭐' me=False count=2>]
Now try getting emoji with Guild.get_emoji with guild it belongs to
@dull terrace
Ok
and which of these properties is responsible for the bot to apply to my message?
The send method?
Every interaction response can be considered a reply
Although real reply would be inter.message.reply but it would never respond to the interaction itself and it shouldn't happen
no, I mean how in this example that the bot would directly respond to the message
not sure, doesn't make sense to me that it'd be able to find the index on the if statement a couple lines above and then fail later
This is a prefix command, for this ctx.reply is used
# async for message in starboardChannel.history(limit=20):
# if message.embeds:
# if message.embeds[0].footer.text == f"Message ID: {message.id}":
# print("Message already in starboard.")
# else:
# if message.reactions[0].count >= starLimit:
embed = discord.Embed(title=f"⭐ {message.reactions[0].count} ", description=f"[Jump to message!]({message.jump_url})", color=0x03befc)
embed.add_field(name="Message Content", value=message.content, inline=False)
embed.set_footer(text=f"Message ID: {message.id}")
embed.set_author(name=message.author.name, icon_url=message.author.avatar)
embed.timestamp = message.created_at
if message.attachments:
embed.set_image(url=message.attachments[0])
await starboardChannel.send(embed=embed)
cursor.close()```
!d discord.ext.commands.Context.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send "discord.ext.commands.Context.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") referenced by this context.
For interaction based contexts, this is the same as [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send "discord.ext.commands.Context.send").
New in version 1.6.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
if i do this it works but doesnt update
oh i see

Why do you need to reply with slash command
how can i resolve this? the code works fine but want to get rid of this error..
@a2m.event
async def on_message(message):
ChatString = message.content
UserName, GameCommand, *rest = ChatString.split(":")
print('UserName: ' + UserName)
print('Command: ' + GameCommand.strip())
print('Additional Arguements: ' + str(rest))
AdminRole = discord.utils.get(message.author.roles, name = "Admin")
# MemberRole = discord.utils.get(message.author.roles, name = "Member")
if message.author == a2m.user:
return
#Discord Admin Check
if message.author.guild_permissions.administrator:
#Xerp Check
if message.content.startswith('Xerp:'):
if ComPrefix + 'test' in GameCommand:
await message.channel.send('Test Passed all Checks, Hello Xerp')
return
if ComPrefix + 'test' in GameCommand:
await message.channel.send('Test Passed all Checks, Hello Admin')
return
#If user does not have the Admin Role.
if not AdminRole:
if ComPrefix + 'test' in GameCommand:
await message.channel.send('Test Passed all Checks, Hello User')
return
Traceback (most recent call last):
File "C:\Users\manes\Desktop\Zomboi A2M\A2M 9 - 7\env\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\manes\Desktop\Zomboi A2M\A2M 9 - 7\a2m.py", line 169, in on_message
UserName, GameCommand, *rest = ChatString.split(":")
ValueError: not enough values to unpack (expected at least 2, got 1)
async for message in starboardChannel.history(limit=100): how are you storing messages
And it is done with inter.send
the problem is that I'm thinking of doing it not through the command, I don't fully know how
idk
yes
!d discord.Message.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message").
New in version 1.6.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
Just get the message object and use this
it's your code but you don't know...
why to store in int??
it will check the embed in the channel history
then it will check if the footer matches or not
Guild.get_emoji does not exists
just store the fields you need and not the whole message
!d discord.Guild.get_emoji
No way, José.
No documentation found for the requested symbol.
All emojis that the guild owns.
@honest shoal try printing these and see if anything prints at all
Meanwhile I am gonna check more docs
I have jishaku, can I use that?
.. @dull terrace
idk how you're storing stuff right now
I guess
bot got crashed anyway, I'll update the code
if i wanted to store emoji reaction counts for messages, i'd use the message id as a primary key in a database and then use a column for emoji_count
Um why store them when you can just get them from discord 🤓
Long-term storage of something stored on discord is pointless imo
ya i am making it
myself
Hey everyone
? if you have tons of people using your bot those extra api calls are gonna bottleneck the crap out of it
Hello
Long-term and cache are different things
I meant cache is more suitable for this
until you need to restart the bot
That's not really a problem
and you have to fetch thousands of messages
Does anyone know if one can make a bot do a voicecall when a message is sent? So but calls a person and gives code which they then have to type in to auth…
Well depends
storage is cheap, why wouldn't you take advantage of it
@dull terrace
Message ID: 1010598292624789554
None
Message ID: 1018527051122233465
Message ID: 1018527051122233465
Message ID: 1018527051122233465
Message ID: 1018527051122233465
Message ID: 1018527051122233465
Message ID: 1018526332428222546```
if message.embeds:
print(message.embeds[0].footer.text)
if message.embeds.footer.text == f"Message ID: {message.id}":
print("Message already in starboard.")
return```
if i do this
nice
but the message already in starboard is not printing even if it is there
okay so one of the messages doesn't exist
i guess just do
async for message in starboardChannel.history(limit=20):
if message.id is None:
continue
if message.embeds:
print(message.embeds[0].footer.text)
if message.embeds.footer.text == f"Message ID: {message.id}":
print("Message already in starboard.")
return```
Anyone know how to make so a discord bot sends a embed with a question and then when someone aswere it will see that and send another embed with another question?
How can I make a custom prefix in the "nextcord" fork?
yes
Help me
idk nextcord
client.fetch_emoji(emoji_id)
- make questions with answers
- send questions
- check for answers in users msg
- then post another ques.
it does not exists unfortunately
there's fetch_sticker but no fetch_emoji
Okey/ i made the embed with the question how old are you and then i made this
async def on_message(message):
if message.channel.name.startswith("application-"):``` and now im stuck because i dont know what to write under.
oh my bad, it's get_emoji
get_emoji is not getting anything
use modals my bro
is your bot in the server with the emoji, is the id correct, does your bot have the right permissions
is it possible to check whether the person answered through the "reply" button or just wrote a message:
async for message in starboardChannel.history(limit=20):
if message.id is None:
continue
if message.embeds:
print(message.embeds[0].footer.text)
if message.embeds[0].footer.text == f"Message ID: {message.id}":
print("Message already in starboard.")
return
else:
embed = discord.Embed(title="Starboard", description=f"**`⭐`{message.reactions[0].count}**", color=0x03befc)
embed.add_field(name="Message", value=message.content, inline=False)
embed.set_author(name=message.author, icon_url=message.author.avatar_url)
embed.set_footer(text=f"Message ID: {message.id}")
await starboardChannel.send(embed=embed)
return```
i dont want to use modals
again same error
embed = discord.Embed(title="Starboard", description=f"**`⭐`{message.reactions[0].count}**", color=0x03befc)
IndexError: list index out of range```
it is there, id is correct I posted screenshots, bot is amin
Is there a method to look for the channel's very first message? I'd like to know. And the documentations as well pls.
if i add this
embed = discord.Embed(title="Starboard", description=f"**`⭐`{message.reactions[0].count}**", color=0x03befc)
embed.add_field(name="Message", value=message.content, inline=False)
embed.set_author(name=message.author, icon_url=message.author.avatar_url)
embed.set_footer(text=f"Message ID: {message.id}")
await starboardChannel.send(embed=embed)
return```
then how are you planning to do
are you passing the emoji id as an integer
yup
im making a application system and i want to answere the question in chat so i need help with making the bot see the aswere the person write and then send another embed with another question
I cannot see any issue is the issue
I'm thinking to give up and use a default emoji instead
if get_emoji was broken you'd print None
you have the emoji and just need to use it?
it printed None
and threw an error which I posted first
but you just showed the code and it printed an emoji object?
how will the applications start?
it printed None, instead of emoji object
are you looking to commission someone to make it for you?
what's the problem
oh also akg, make sure your bot is ready
if you try to fetch it before on_ready() it'll return None
"Pebblehost" does not have discord.py installed for whatever interpreter you're using
i got nothing as discord.py and the files works fine in pycharm
also i got import discord
Do you understand the difference between running python locally and on a virtual server's python installation?
The interpreters are different and do not have the same 3rd party libraries installed
yeah, i have the package downloaded myself in cmd but in pebble i had download the packages too
Well I can't debug for you but the error indicates it isn't
Perhaps the versions are mismatched
pretty sure you don't need to install dependencies in peeblehost yourself
you just provide a requirements.txt with all the deps
sorry for abt that, but whats the requirements.txt must include? i dont get it
can you show us a screenshot of your peeblehost setup
yeah, for sure
ok i got it running now the requirements.txt wasnt in
but i dont understand what is it for?
i just found it in stackflows but no explanation
welp, as the name suggests it's a file containing a list of libraries required to install
So does anyone know how i can go about handling my error? or point me in the direction of fixing it? as i said the code works proper as it ignores the exception but im not sure how to figure out how to check for it
What's the error
Ohhhh
I need help again
The message didn't have any ":" in it then
If you're on dpy 2.0 make sure your message content intents are enabled. And remember that on_message goes through all messages the bot can see
Suggestions on how i can make the bot give roles according to points
hi so basically i started coding like 1 mintue ago for the first time and i wanna make this thing where when u open the file it turns the bot online
i did the first part but how do i put that when i turn on the file the bot runs
import discord
from discord.ext import commands
import random
from discord import Permissions
from colorama import Fore, Style
import asyncio
token = "Bot token"
but this at the end
bot.run(token)
intents = Intents.default()
intents.message_content = True
BOT_PREFIX = "$"
bot = commands.Bot(command_prefix=BOT_PREFIX, intents=intents)
this under the imports
and an on_ready event to see if the bot is online
?
async def wfl(ctx, arg1):```
when theres a space in the input, arg1 will only take the first argument when calling this command
how do i take an infinity of arguments
just make it a kwarg with a star(*)
just add it before arg1
async def wfl(ctx, *args?)?
add a coma and remove the question mark!
idk
@bot.command()
async def wfl(ctx, *, arg1):
e.g
oh ok thank you
with commands, is it possible to do .lower() to the command the user uses
pardon? like an alias?
or is the only way to make multiple functions
!d discord.ext.commands.Command.aliases
The list of aliases the command can be invoked under.
id like Wfl, and wfl to be the same command, but making a diff function sounds like a caveman practice
ok thanks
yep an alias!
is there a way to toggle an "on_message" function only after a specific command has been used?
!d discord.ext.commands.Bot.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.10)"). 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.10)") 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.10)") 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**...
hi i wanna make a tool like .exe when u open it runs the bot
i just started coding today so idk can someone do it il send code
I'll take a look at it, ty!
Like run a bot from an executable?
!pypi pyinstaller
but i wanna connect it to a tool
like connect code to a exe and when i run exe bot turns on
you can just make the executable run a file
but why exactly?
!d os.system | which you can just invoke python from a command, you can just do it in python and then turn the python file to an executable with pyinstaller i wouldnt recommend it tho
os.system(command)```
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function `system()`, and has the same limitations. Changes to [`sys.stdin`](https://docs.python.org/3/library/sys.html#sys.stdin "sys.stdin"), etc. are not reflected in the environment of the executed command. If *command* generates any output, it will be sent to the interpreter standard output stream. The C standard does not specify the meaning of the return value of the C function, so the return value of the Python function is system-dependent.
On Unix, the return value is the exit status of the process encoded in the format specified for [`wait()`](https://docs.python.org/3/library/os.html#os.wait "os.wait").
@bot.command(aliases=['Wfl', 'WFl', 'WFL', 'wFL', 'wfL', 'wFl'])
async def wfl(ctx, *, arg1):
```i understood with a forum
it rly isnt clear how to implement it in the documentation :/
at least the docs let you know of whats possible
its a kwarg of the commands.Command that accepts a list of strings(list[str])
no need for the brackets in the function name
ah yh my bad i was testing someting
If you want to make the bot case insensitive this is not the right way
What library is this
Db library
Why did it suddenly get so popular 🤔
Probably because of some yt tutorial
u supposed to do result = fetch...ect
that is normal
it gives 1, 2 or 3 as output for saying it updated, or not, or added a new thing in the db
- Don't use f-strings, use placeholders just like you did first time
- I don't really know how exactly is it done in aiomysql, but I suspect that you need to do something like
res = await cur.fetchone(...)instead ofexecute
yo how master
Sorry what
There's a kwarg in bot init
commands.Bot(case_insensitive=True)```
Np
how do i replace things in a text file
if a proper file, u need to use beautiful soup
and it allows u to change stuff
from discord.utils import get
@bot.command(pass_context=True)
async def purge_members(ctx):
for member in ctx.message.server.members:
if not get(member.roles, name='calls'):
else not get(members.roles, name='notifications'):
await bot.kick(member)```
guys this would kick members without the calls and notifications role right?
Not really that's invalid syntax
You can check if the user doesn't have the calls and notifications role like so:
if not (get(member.roles, name="calls") and get(member.roles, name="notifications")):
# kick user
oh yea alr
idk lmfao, i havent coded ina while and cba to revise but gotta make a disc bot carry out a command to purge/kick members without specifc role/s
oh mkay
It's not a thing
I'm guessing they mixed up elifs and elses
ugh my system clock is fucked again i need to figure out how to fix it
^
@sick birch
@client.event()
async def on_ready(ctx):
for member in ctx.message.server.members:
if not (get(member.roles, name="calls") and get(member.roles, name="notifications")):
await client.kick(member)```
This would make it so whenever i just run the bot it runs that code ye?
well kind off, just wanted to test
the question is can I make a check if the person answered the message of the bot using the "reply" button?
!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.10)"). 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.10)") 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.10)") 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**...
why do you need it?
I thought u were a diff person than the person who asked the question, got a bit confused
U could use it for a giveaway bot where u wait for a message in the channel the bot is in, so they don't need to add it as a parameter
I know some messages have the : and some will not. I want it to go to something else if the error occurs. As I said the code works I just didn't know how to handle and ignore the error
'try except' (don't use a bare except, add ur error to it)
Ah thank you very much
Ty that worked
people like making bots for certain game discords and storing data, for what theyre trying to do as i think most of them are, itd be easier honestly using a json instead, turns stress into 6 lines of code
Using a module, what?
How can I turn this (1st pic) into this (2nd Pic)?
My code goes like this ```py
ServerInfoEmbed.add_field(name="Creation:", value=f"{inter.guild.created_at}", inline=True)
So that the Bot will only say: days, weeks, months or years instead of being overly specific
Also, help me out guys.. Will be going offline in a few more bit
I guess just tell me what method to use or what to change. For now, I gtg lol. I'll check replies later
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
If you use json stress is going to get much more intense as the file gets bigger, don't use json as database. My question was about "why are people using concretely mysql", like why not sqlite or postgres
I like postgres
One reason i can think of is that MySQL is taught in Indian schools, and consider the % of Indians in this channel
f' <t:{ctx.guild.created_at.timestamp():.0f}:R>
I think that's just some "popular" yt tutorial
Because indians always have been here and I started to frequently see mysql questions here not really long time ago
True but a discord bot youtube tutorial using a database seems impossible
Yes lmao
How can i fix this
Do you have any tasks on startup or loops
can anyone help me with pymongo, i have the whole adding things to database working but when i try to use the collection.find then and print 'snippet' it just ends up printing this <pymongo.cursor.Cursor object at 0x00000252D5DA3D60> and idk how im supposed to print the snippet data. if anyone could help id appreciate it
What about #databases
for n in snippet:
# whatever
n['snippet'] should give the value
hello can anyone help me send a body request to a website?
conn.request("POST", "/giverole", json.dumps({"discord_id": %s, "account_name": username}), headers)
What's conn?
the %s in the dict wouldn't valid syntax
run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., root_logger=False)```
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.start "discord.ext.commands.Bot.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.connect "discord.ext.commands.Bot.connect") + [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login").
This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.
Warning
This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
discord doesn't allow selfbots
No selfbots xdxd
why u delet 
Discord changed delete button relative placement, now my kinematic memory always makes me press copy
Is there a way to disable confirmation message on mobile
Like I don't have shift here
I have made the bracket with the error bold
@bot.command()
async def steal(ctx, member:discord.Member):
if member == None:
guild = ctx.guild
member = random.choice(guild.members)
await open_account(ctx.author)
await open_account(member)
users = await get_bank_data()
member_account_val = users[str(member.id)]["Wallet"] - 50
if member_account_val == 0:
await ctx.send(f"{member.mention} caught you stealing them")
amount = random.randrange(0, member_account_val)
users[str(member.id)]["Wallet"] -= amount
users[str(ctx.author.id)]["Wallet"] += amount```
this is my code
I am getting a error in the random range line
so basicly I am making a economy bot
u following YT tutorial?
that stores the user id and the value in a josn file
No?
ye, u'll always get errors
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: empty range for randrange() (0, -50, -50)
this is the error
ohk, I have seen a very identical code on YT which also uses json to store data...
but ok
I did it in like 15 - 20 mins
u think am lying
just ask me something
no no chill
bruh can u please help me with this random range error
How do i get the media link to messages that have file attachments?
Did you fix it?
can u send the basic code?
Wat?
of the embed or the msg
Embed
nAH 😦
await ctx.send(file=discord.file(fp="(your_file_name).jpg", filename="image.jpg"))
#.jpg is just an example, it can be what the file type is```
Bro
fp is filepath
Not send, get
ohk, mbmb
this maybe?
https://stackoverflow.com/questions/61898621/getting-the-url-of-an-attachment-in-discord-py
Looks like that error raised because you gave it negative number
but it's not
how??
can u tell me some alternative tehen?
The error says otherwise
You can't put a negative number as second parameter
Thanks bro that worked somehow even tho i swear i tried that exact thing before
@bot.command()
async def noroleskick(ctx):
# iterate through guild members and kick members with only 1 (@everyone) role
# increase kicked counter +1 for each kicked member
guild_members = ctx.guild.members
kicked = 0
for member in guild_members:
if len(member.roles) == 2:
# print(member.display_name)
await member.kick()
kicked += 1
# If any members were kicked, send message with number of kicked members
if kicked > 0:
await ctx.send(f'{kicked} members were kicked from the server.')
This would kick members with the @ everyone and @ members role yeah? Basically if they have 2 roles it would kick em
is there any way to convert a negetive number into positive?
???
Why would you want to 
or it will simply don't work
# if user has postive amount of balance
amount = random.randint(0, member_accont_val) ```
You can just check if the number is lower than 1
Damn, most of these questions are non discord bot related xD
gotcha
🧍♂️ discord api counts @ everyone as 1 role ye?
Try it without kicking actually
You can get a member object and just check his roles
async def b(user:discord.User):
db = await aiosqlite.connect("bal.db")
cursor=await db.cursor()
await cursor.execute(f"SELECT * FROM Balance WHERE user_id = {user.id} ")
if result:
return
if not result:
await cursor.execute(f"INSERT INTO bal(user_id, cash, crystals, event_pearls, weapon_shards, fusion_earring, merging_stones, enhancing_stones) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (user.id, 500, 0, 0, 0, 0, 0, 0, 0))
await db.commit()
await cursor.close()
await db.close()
@bot.command(aliases=['bal'])
async def balance(ctx, user:discord.User=None):
if user is None:
user = ctx.author
await b(user=user)
db = await aiosqlite.connect("bal.db")
cursor = await db.cursor()
await cursor.execute(f"SELECT * FROM Balance WHERE user_id = {user.id} ")
balem=discord.Embed(description=f"**{user.metion}'s balance**", color=discord.Color.blue())
balem.add_field(name="Cash:", value=f"{result[1]}", inline=False)
balem.add_field(name="crystals:", value=f"{result[2]}", inline=False)
balem.add_field(name="event pearls:", value=f"{result[3]}", inline=False)
balem.add_field(name="weapon shards:", value=f"{result[4]}", inline=False)
balem.add_field(name="fusion earring:", value=f"{result[5]}", inline=False)
balem.add_field(name="merging stones:", value=f"{result[6]}", inline=False)
balem.add_field(name="enhancing stones:", value=f"{result[7]}", inline=False)
await ctx.send(embed=balem)
```
No error with the code itself but when I run the script (server_prefix) bal nothing happends, it doesn't give any errors, nor does it update send an embed, nor does the db get updated
PS - The db is aiosqlite
Try changing discord.User to discord.Member
ye, I already did that, I just changed it before sending it here
Did it work?
nope
ye, but lemme just check
Add some prints, so you can see where the code stops ig
how do i fix it crashing when only an image is sent ```py
@client.event
async def on_message(message):
channel_final = client.get_channel(942848242616516638)
channel_final_mi = client.get_channel(640107632690200587)# channel to ping message if approved
button1 = Button(label="Approve!",style=discord.ButtonStyle.green)
button3 = Button(label="Disapprove - No Mute", style=discord.ButtonStyle.blurple)
button2 = Button(label="Disapprove!",style=discord.ButtonStyle.red)
view = View()
view.add_item(button1)
view.add_item(button3)
view.add_item(button2)
message_channel = message.channel.id
user_id = message.author.id
channel_sent_in = message.channel
# Check if message has content
if message.content is not None and message_channel in [1017792577740734536, 1018468004121542716]: # Add message content to list
msg_list.append(message.content)
await message.delete()
print(msg_list)
comhelper = '<@&889878315089932328>'
staff = '<@&810238562053914695>'
admin = '<@&811310504471035935>'
channel = client.get_channel(1017118446284177419) # channel where checked if post is good
embed = discord.Embed(title=f'Message detected in #{channel_sent_in}', color = 10181046)
embed.add_field(name='Message: ', value=f'{message.content}')
embed.add_field(name='User: ', value=f'{message.author}')
embed.set_image(url=message.attachments[0].url if message.attachments else None)
embed.set_footer(text=f'Provided by Donks#1048 • {current_time}')
await channel.send(f"Here: {comhelper + staff + admin}")
await channel.send(embed=embed, view=view)
k, it wasn't turned on I have turned it, let me retry
Any errors?
intents.message_content = True
I had to this, right?
Yup
Ah yes let me send
await channel.send(embed=embed, view=view)```

the file is .db, could that be an issue?
k
Is that an error?
yes
its cause py embed.add_field(name='Message: ', value=f'{message.content}') embed.add_field(name='User: ', value=f'{message.author}')
these r not being filled if only image
What do you mean by crashing?
well not crashing in a sense, but it will just go over it
and miss code out
as if only an image is sent, message content wnt work
It's because this line
what would i change? 🙂
Eh, just remove "message.content" from the if statement and check if the message has any content and put it in the field. If not, then put none instead
if message_channel in [...]:
...
embed.add_field(
name='Message: ',
value=message.content if message.content else None,
)
hmm still get error if only image is sent
Ah it works now
If now no message is sent, how would i make it say something else?
Just change from None to something else
embed.add_field(
name='Message: ',
value=message.content if message.content else 'Something else',
)
!e py bruh_var = "bruh" bruh1 = f"{bruh_var}" # what the heck for print(bruh_var == bruh1)
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
True
import lightbulb
bot = lightbulb.BotApp(token="
", prefix="-")
@bot.command
@lightbulb.command("ping", "checks the bot is alive")
@lightbulb.implements(lightbulb.SlashCommand)
async def ping(ctx):
await ctx.respond("Pong!")
bot.run()
My bot ain't replying :/
this is the first time i’ve ever seen someone try and do it like this o:
Very cursed
can i ask what made you go that route?
xd
?
Alright am back. I asked the question (In reply)
and got this answer:
f' <t:{ctx.guild.created_at.timestamp():.0f}:R> (This worked btw)
But what does these parts of the code mean?
f' <t:{ctx.guild.created_at.timestamp():.0f}:R>
This was a first I've worked using datetime so I'm kinda dumb when it comes to these lol
Timestamp for when the server(guild) was created
Some1 said me this library is better than other libraby
I was using nextcord
Hi everyone, what means this following error shard id heartbeat blocked
XD
Yeah, I guess it's time to learn more about datetime lol. I still can't get what these symbols do
<t: :.0f :R>
Thanks for the response though
Discord's timestamp syntax
Makes sense. Thanks lol. I'll watch more Python Basics before I really try to do anything. Just to be on the safe side Kek.
Thanks again
anyone got any experience with cloudfare hosting in terms of quality?
Cloudflare doesnt do hosting?
Accord to discord dev logs they do. Cant show Atm as im replying on apple watch =3
lightbulb 😳
lightbulb is surely better than forks imo
plus the command handling is done in a better way
especially for hybrid commands
folks 😳
autocorrect, Ryuga. lol
what's the error though
enable the message content intents
wait wdym by not replying, its a slash command...
Hi, my msg delete button is not working. Following is the error: console The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/disnake/ui/view.py", line 370, in _scheduled_task await item.callback(interaction) File "/app/main.py", line 322, in delete await inter.delete_original_message() File "/app/.heroku/python/lib/python3.10/site-packages/disnake/interactions/base.py", line 532, in delete_original_message raise InteractionNotResponded(self) from e disnake.errors.InteractionNotResponded: This interaction hasn't been responded to yetAnd this is the code:```py
class Delete(disnake.ui.View):
def init(self, inter: disnake.ApplicationCommandInteraction):
super().init(timeout=43200)
self.inter = inter
@disnake.ui.button(emoji=jot, custom_id='delbutton')
async def delete(self, button: disnake.ui.Button, inter: disnake.MessageInteraction):
if self.inter.author.id != inter.author.id:
return await inter.response.send_message("Hey! You can't do that!", ephemeral=True)
await inter.delete_original_message()```
read the error, the interaction inside the button acts for the interaction that took place when the button was clicked, not when your slash command was invoked
🤔then where I'm messing up? I think it's fine
is it inter: disnake.MessageInteraction thing?
class disnake.MessageInteraction```
Represents an interaction with a message component.
Current examples are buttons and dropdowns.
New in version 2.1.
I changed it to ApplicationCommandInteraction, but still it doesn't work
what database package should I use with discordpy?
In your buttons class, define init and put some default variables, such as "message" or whatever. and when you need to call it, parse it as a variable and set the message variable to the message itself.
then when the button is pressed, it edits the message with the new buttons
have you chosen a db yet (looking for an async wrapper)
or a new db
yes then set your variables. like self.message etc
id say postgres or sqlite
ty
no
def __init__(self):
super().__init__(timeout=None)
self.message = ''
then when you want to add buttons do:
mybuttons = MyButtonsClass()
mymessage = await interactions...(view=mybuttons)
mybuttons.message = mymessage
then in the MyButtonsClass when a button is pressed, edit the message with a new view
Lemme quickly whip some shit up as an example. idk if im explaining it correctly
Any asynchronous package will do
import discord
from discord.ext import commands
from discord import app_commands
class test(commands.Cog):
def __init__(self, client):
print("[Cog] My Test has been initiated")
self.client = client
@app_commands.command(name="test", description="test")
async def test(self, interaction: discord.Interaction):
mybuttons = AnswerButtons()
mymessage = await interaction.response.send_message("Hello World", view=mybuttons)
mybuttons.message = mymessage
class AnswerButtons(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.message = ''
@discord.ui.button(label="Answer this question.", style=discord.ButtonStyle.green)
async def answer(self, interaction: discord.Interaction, button: discord.ui.Button):
newbuttons = NewButtons()
message = await interaction.message.edit(content="Nope.", view=newbuttons)
newbuttons.message = message
class NewButtons(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.message = ''
@discord.ui.button(label="Go Back", style=discord.ButtonStyle.green)
async def goback(self, interaction: discord.Interaction, button: discord.ui.Button):
newbuttons = AnswerButtons()
message = await interaction.message.edit(content="Hello", view=newbuttons)
newbuttons.message = message
async def setup(client):
await client.add_cog(test(client))
ofc this will result in an interaction failed. so you may need to do a interaction response
maybe like "await interaction.response.send_message("Thanks")" and delete it right away? idk
but it works
oh wait
it's await interaction.message.edit_message lol
not await interaction.message.edit
Checked some older code that does something similar coz I was wondering how I handled the interaction thing, and apparently I wrote this code wrong xD
yeah so it's just this:
import discord
from discord.ext import commands
from discord import app_commands
class test(commands.Cog):
def __init__(self, client):
print("[Cog] My Test has been initiated")
self.client = client
@app_commands.command(name="test", description="test")
async def test(self, interaction: discord.Interaction):
mybuttons = AnswerButtons()
mymessage = await interaction.response.send_message("Hello World", view=mybuttons)
mybuttons.message = mymessage
class AnswerButtons(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.message = ''
@discord.ui.button(label="Answer this question.", style=discord.ButtonStyle.green)
async def answer(self, interaction: discord.Interaction, button: discord.ui.Button):
newbuttons = NewButtons()
message = await interaction.response.edit_message(content="Nope.", view=newbuttons)
newbuttons.message = message
class NewButtons(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.message = ''
@discord.ui.button(label="Go Back", style=discord.ButtonStyle.green)
async def goback(self, interaction: discord.Interaction, button: discord.ui.Button):
newbuttons = AnswerButtons()
message = await interaction.response.edit_message(content="Hello", view=newbuttons)
newbuttons.message = message
async def setup(client):
await client.add_cog(test(client))
How do i use slash and prefix command at same time, i mean that i want to use a command as slash and prefixed with out writing the code two times
Put the code itself into a function, and have the commands redirect to the function
@app_commands.command(name="test", description="test")
async def test(self, interaction: discord.Interaction):
await self.mycodefunction()
@commands.command()
async def test2(self, ctx):
await self.mycodefunction()
async def mycodefunction(self):
mycode goes here.
```@light violet
Alternatively if you want, create a separate class entirely
Is it possible to do a command like /tableflip? where it appends to my message?
Like, you know how when you do the /tableflip command it appends that stuff to the end of your message. Can I make other commands?
I dont think you can have 1 function assigned to both a slash command a text command
!d discord.ext.commands.Bot.hybrid_command
@hybrid_command(name=..., with_app_command=True, *args, **kwargs)```
A shortcut decorator that invokes [`hybrid_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.hybrid_command "discord.ext.commands.hybrid_command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.add_command "discord.ext.commands.Bot.add_command").
yea
thats neat
I wanna make a casino bot so how can I do it when I type .money that shows the money of a player he earned
You need to store the data somewhere
Im a really really beginner