#discord-bots
1 messages · Page 91 of 1
I get it you make personal server bots then
Doesn't work?
How to download a module in python
pip install module
Wdym it's not printing that the bot is on
How can I programm a music bot
Youtube music?
youtube or spotify
I found some hardware to store the bot
I mean to host it
How much ram does it take on average
Also what are some usefull tips if I'm trying to sell the bot
Security wise
You don't need any more than 8 gigabytes of RAM for just the bot unless it's going to use very big runtime resources
Don't let them run arbitrary Python code like in eval or in exec and preferably limit their access to the internet
2-4 gb is enough aswell
please helpp
Does it print without persistent views on ready?
PLEASE HELLPP
^^
No error? xd
Enabled message content intents?
how i enable that
Brruh
!intent
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
Dm me if you are a good developer
What is a good developer
That's a lot of errors xd
I need a developer to code me a bot
Notepad? :o
You need message_content intent
Where i add it
Great quesiton! 😄 I was just about ask similar. 😉
With the other intents you're enabling
is this good?
but it does send message
when i ping him like @slate swan it says but when i do other cmds they dont show
What
You need message_content intent to get message content from a message
and how i do that
I am good
where i type it
Read the tag
is the bot online?
For $?
I'm not asking or offering paid work
isn't your async def on_ready indentation fked?
good??
message_content not members intent why aren't you understanding this
but that code is in my code
it's on the same line as def init
no? xD
How you going to code in python without knowing python
the code is from github
There are many free courses online, you can take one
is that the whole ss ?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Ayo spoonfeeding isn't allowed here
Yeah so teach him, don't spoonfeed
xD
no
the pastebin one
what i need to do from that code
this is the only message it can send
You have only shown the main file, not all the others (please don't though). You need to really contact the owner of the bot or read its documentation to understand it better, there shouldn't be any reason to change anything if you have downloaded it from GitHub.
Google it how to manipulate a picture like that, and then implement it on Discord bot
Just so you know, instead of
async def petpet(ctx, *, member: discord.Member = None):
member = member or ctx.author
...
you can do
async def petpet(ctx, member: discord.Member = commands.Author):
...
Also line 3140 is unnecessary and I don't know how gen_petpet nor how generate_image are implemented so I can't help if they are erroneous
How many lines of code do you have @slate swan ?
I know, right? I would split my project into several files
We can help
How do I get the user's badges shown as emoji?
No
How many modules have you imported? xd
Hahaha
It would take him a whole day to organize his functions into cogs xD
Try making it yourself first
mhm
Just use asyncio.sleep with while true event
He meant ratelimit ig
Like
@bot.slash_command(name="stats")
async def stats(interaction: nextcord.Interaction):
#create channels stuff here
while True:
#update channels
asyncio.sleep(5)```
What?
That's how it would work
So it updates every 5 seconds (I think)
I can't remember time formatting for async
You can only change the channel name 2 times in 10 minutes + you'd want to use tasks.loop for updating the channel names, no?
That could work both ways work
My way would require less code
So whenever bot does a restart then your method wouldn't work anymore
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
You need to store the ID of the channel somewhere in order to retrieve it in the function
If it's a single server bot, storing the ID in a bot variable is good enough
,
It just calls a function that edits the category every now and then
That's how you would want to define the function for the task
Then store state channel IDs in a database of some sort and have the task go through each one and update it according to the channel's server
less code is not always good code
plus a while loop? definitely not an option when you can use the async version for loops
10 points for creativity
discord.py is back and booming
plus it's py-cord not pycord. They are different libs
I mean, disnake existed way back
nextcord could be considered too
I know that it's a fork smh
Nextcord is best fork in my opinion
disnake is. end of discussion
What kind of bot commands
Well do ctrl + f and search @bot.slash_command
last time I remember making a bot, my bot.py only had the BotApp subclass
lmaao
smh
Well I don't know whether slash commands appear in bot.commands in pycord
py-cord*
hyphens are cute ngl
Did you follow the example correctly?
You also have to modify the Ticket view
Compare these two views and see if your have smth different
Send a picture of your ticket view
well well well
spot the difference
Also why is your ticket buttons in different classes?!
Yeah
Define a simple View that persists between bot restarts.
In order for a View to persist between restarts it needs to meet the following conditions:
1) The timeout of the View has to be set to None
2) Every item in the View has to have a custom_id set
It is recommended that the custom_id be sufficiently unique to
prevent conflicts with other buttons the bot sends.
For this example the custom_id is prefixed with the name of the bot.
Note that custom_ids can only be up to 100 characters long.
Follow these requirements
What are you trying to do?
Use interaction.original_response to get the message
!d discord.Interaction.original_response
await original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the original interaction response message associated with the interaction.
If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).
Repeated calls to this will return a cached value.
py-cord sigh
I don’t think that’s pycord
it is
Which part of pycord?
This?
hey, got a question, im having an error called "main() takes 0 positional arguments but 1 was given".
what is a positional argument?
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
py-cord*
what do you mean by part?
they clearly mentioned that it's py-cord
Nvm
im setting a discord bot, im having this error msg after implementation
where should i go then
ok thanks.
Has disnake completely migrated to slash commands or hasnt happened yet?
is it possibe to limit a function to only one server? lets say python code can somehow check if its in a certain server and then if it is in that server a command becomes available
#user dms bot
#creating blocked user database
@commands.Cog.listener()
async def on_ready(self):
self.bot.db=await aiosqlite.connect('blocked.db')
await asyncio.sleep(3)
async with self.bot.db.cursor() as cursor:
await cursor.execute('CREATE TABLE IF NOT EXISTS blocked(user INTEGER)')
await self.bot.db.commit()
#block user command
@commands.command()
@commands.has_permissions(administrator=True)
async def block(self, ctx, member:nextcord.Member,*,reason=None):
async with self.bot.db.cursor() as cursor:
await cursor.execute('INSERT INTO blocked VALUES(?)',(member.id))
await self.bot.db.commit()
await ctx.send(f'I have blocked {member.mention} from sending me messages for reason: {reason}')
return
could someone help me with this error?
Ignoring exception in command block:
Traceback (most recent call last):
File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 165, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\kouxi\Runa\cogs\moderation.py", line 121, in block
await cursor.execute('INSERT INTO blocked VALUES(?)',(member.id))
File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\core.py", line 129, in _execute
return await future
File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\core.py", line 102, in run
result = function()
ValueError: parameters are of unsupported type
discord IDs are BIGINT, not INTEGER
any nice project ideas
use custom checks or just check the guild ID inside the command
is it possibe to limit a function to only one server? lets say python code can somehow check if its in a certain server and then if it is in that server a command becomes available
I just replied...
i changed the table to 'CREATE TABLE IF NOT EXISTS blocked(user BIGINT)' and it still gave me the same error
also i have some other databases for leveling up and stuff, and it works fine with user being set to INTEGER?
the table already probably exists, which is why it still errored. Also, your tuple isn't really a tuple
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
probably the same thing
you can also make it an ephemeral message
im trying to create a database of a list of users so the bot can "block" them
when anyone dms the bot, the bot checks if their user id is in the table, and if it is, the function returns. if the id isnt in the table, the user isnt blocked, and the bot forwards the message to the mods in the server
so it only shows up for the person who clicks it
that's against TOS
i dont think it can but idk
making your bot create invites to a server so that you can join it
how come my other databases with user INTEGER work and not this one?
wdym "globalchat"?
idk, you're probably doing something else. Either way, you're passing (member.id), you should be doing (member.id,) (notice the coma). Cause otherwise (member.id) would be equivalent to member.id, and you don't want that do you?
no, I don't
ah that fixed it, thank you so much
ah
Not possible
You can create invites but users can't join
Since bot invite link is only usable by other bots
since when
Since always…
and bots cant join unless an admin invites them
Well that's true but my theory is if they could join servers they could use that link
so you’re telling me if i made an invite for a server with a bot, i wouldnt be able to join?
they can??
Yes but there pointless
Correct
a user can join with an invite created by a bot, wdym
I figured it out myself
They can't
you might want to do some better testing
!d discord.TextChannel.create_invite
await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates an instant invite from a text or voice channel.
You must have [`create_instant_invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_instant_invite "discord.Permissions.create_instant_invite") to do this.
Yup that's it
hey @slate swan i have an answer to your question of joining servers your bot is in
you’re telling me
if i sent you that invite
you wouldnt be able to join?
Yup
do you mind me sending you the invite?
Nope try it
can you send a screenshot of what happens when you try and click it
Sure
theory debunked 👍
np
how can i add a user to the channel?
!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...
pass member as the target
import discord
from discord.ext import commands
import aiohttp
client = commands.Bot(command_prefix="y.",intents=discord.Intents.all())
TOKEN=no
@client.event
async def on_ready(): #remove later?
print('bot is ready')
@client.event
async def bruh(ctx):
async with aiohttp.ClientSession() as cs:
async with cs.get(url of a page) as r:
print(r)
client.run(TOKEN)
discord.ext.commands.errors.CommandNotFound: Command "bruh" is not found
change the @client.event to @client.command()
np
you need a TextChannel instance, and using that instance you set the permissions
import discord
from discord.ext import commands
import aiohttp
client = commands.Bot(command_prefix="y.",intents=discord.Intents.all())
TOKEN=no
@client.event
async def on_ready():
print('bot is ready')
@client.command()
async def bruh(ctx):
async with aiohttp.ClientSession() as cs:
async with cs.get(url of a page) as r:
print(r)
client.run(TOKEN)
how do i print the html of a page
im trying to webscrape but people have told me that "requests" module should not be used
await r.read()
async with cs.get(url of a page) as r:
await r.read()
that?
requests is blocking, which is why you shouldn't be using it. Also, please make sure you're compliant and aware of the website's TOS, as they might not allow webscrapping
correct
you have to make a cooldown event
use an error handler to catch the exceptions
for my slash bot it looks like this @tree.error async def on_app_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError): if isinstance(error, app_commands.CommandOnCooldown): await interaction.response.send_message(error, ephemeral=True) else: raise error
do i still need to use beautifullsoup?
depends on what you're trying to do/how you want to do it
ok
i use this in my text bot @bot.event async def on_command_error(ctx, error): if isinstance(error, commands.CommandOnCooldown): cd = round(error.retry_after) minutes = str(cd // 60) seconds = str(cd % 60) embed = discord.Embed(title="Oop, something went wrong!", description=f"Try this command again in {minutes} egg whites, and {seconds} egg yellows", color=color) embed.set_footer(text=footer) await ctx.send(embed=embed) if isinstance(error, commands.CommandNotFound): await ctx.send("I could not find that command. Use M.help to see al the commands.")
@client.command()
async def func(ctx):
results=requests.get(url of a page)
doc = BeautifulSoup(results.text, "html.parser")
vallist= doc.find_all("span")
someting like that
👌
try it and see. Change requests with aiohttp though. However I don't think this'll be the correct place for your questions as this isn't really discord bot-related anymore
ok tnc
also i think i did someting wrong
cos this is not working :
async def bruh(ctx):
async with aiohttp.ClientSession() as cs:
async with cs.get(url) as r:
await r.read()
print(r.read())
i think i misunderstood something
^
!d discord.ext.commands.Command.error you can use this to make a command-only error handler
@error```
A decorator that registers a coroutine as a local error handler.
A local error handler is an [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event limited to a single command. However, the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") is still invoked afterwards as the catch-all.
Changed in version 2.0: `coro` parameter is now positional-only.
you need to await r.read. You're printing it without awaiting it
so await r.read():
print(r.read())
no, that'll give you a syntax error
i dont understand
you need to await it
do you have any experience with asyncio?
not much
you don't just "await", you have to await SOMETHING, and that SOMETHING is r.read(), because r.read() is a COROUTINE, and COROUTINES have to be awaited
I can send any code if needed
i do get that what i ment by "just await" was so just the await r.read()
bc it doesnt print it out
read the error, you've got 2 commands with the same name
import discord
from discord.ext import commands
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
print("f Loaded.")
@bot.command()
async def hi():
embed = discord.Embed(title="Elusive - API", color=discord.Color.from_rgb(0, 64, 255))
embed.add_field(name="hi", value="hi", inline=False)
embed.set_image(url="https://cdn.discordapp.com/attachments/971538759516581888/971585692016709663/ezgif.com-gif-maker_1.gif")
await ctx.send(embed=embed)
bot.run("token is acc here just remvoed",bot=True)
none of the commands work not even the help command, no errors and it does print "f Loaded" on start
still got an error after fixing that
you don't await something once, and then call the same function without awaiting it. Each time you call it, you gotta await it to get the result
send new traceback then
you gotta enable message_content intents
intents.message_content = True
correct
same error, you've got 2 or more commands with the same name/alias
that line errors
i dont tho lol can u hop in a vc rq
send updated code/traceback then
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="$", intents=intents)
@bot.event
async def on_ready():
print("f Loaded.")
@bot.command()
async def hi():
embed = discord.Embed(title="Elusive - API", color=discord.Color.from_rgb(0, 64, 255))
embed.add_field(name="hi", value="hi", inline=False)
embed.set_image(url="https://cdn.discordapp.com/attachments/971538759516581888/971585692016709663/ezgif.com-gif-maker_1.gif")
await ctx.send(embed=embed)
bot.run("token is here",bot=True)```
Traceback (most recent call last):
File "C:\Users\User\Desktop\ELUSIVE-API\a.py", line 4, in <module>
intents.message_content = True
well apparently you do, no, I can't hop in vc
send the whole traceback
u dont have to talk i wanna showu
that is the whole traceback
in console tho ill check in vs code
PS C:\Users\User\Desktop\ELUSIVE-API> py a.py
Traceback (most recent call last):
File "C:\Users\User\Desktop\ELUSIVE-API\a.py", line 4, in <module>
intents.message_content = True
AttributeError: 'Intents' object has no attribute 'message_content'
update your dpy
whats the command
I rather not
do i just pip install it again in a batch file
have intents enabled on dev app?
if you're using discord.py python3 -m pip install -U discord.py iirc
do i run that in a batch file
this doesnt work
in your terminal
could you just please end my suffer and tell me how do i print it
@slate swan you might want to check this out after updating too: https://discordpy.readthedocs.io/en/stable/migrating.html
traceback?
I'm already telling you how to print it
you didnt?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object of type 'method' has no len()
read the error bruh
send code
print("")
@client.command()
async def func(ctx):
async with aiohttp.ClientSession() as cs:
async with cs.get(url) as results:
doc = BeautifulSoup(results.text, "html.parser")
await ctx.send(doc)
so how would it look like?
i installed it through the microsoft store nothing changed
i installed 3.10*
and i ran the command in terminal and it worked but same error
same way you're doing it with ctx.send, just change it to results.text
are you using a venv? make sure you're using the correct python version
which version am i supposed to have
i have 3.10 rn
use py -3 a.py then, otherwise you might be using python 2.7
@client.command()
async def func(ctx):
async with aiohttp.ClientSession() as cs:
async with cs.get(url) as results:
await results.text
doc = BeautifulSoup(results.text, "html.parser")
await ctx.send(doc)
he can't use py 2.7, py >=3.8 is required
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object method can't be used in 'await' expression
is this saying i dont even have python on my computer
you're almost there. You gotta call the function, and you gotta move it to the first argument of the BeautifulSoup class
call what function
py -0 for available pythons, not -0
results.text...
i dont fully get it
!function
Calling vs. Referencing functions
When assigning a new name to a function, storing it in a container, or passing it as an argument, a common mistake made is to call the function. Instead of getting the actual function, you'll get its return value.
In Python you can treat function names just like any other variable. Assume there was a function called now that returns the current time. If you did x = now(), the current time would be assigned to x, but if you did x = now, the function now itself would be assigned to x. x and now would both equally reference the function.
Examples
# assigning new name
def foo():
return 'bar'
def spam():
return 'eggs'
baz = foo
baz() # returns 'bar'
ham = spam
ham() # returns 'eggs'
# storing in container
import math
functions = [math.sqrt, math.factorial, math.log]
functions[0](25) # returns 5.0
# the above equivalent to math.sqrt(25)
# passing as argument
class C:
builtin_open = staticmethod(open)
# open function is passed
# to the staticmethod class
@patent wagon you should probably learn some async programming before you tackle dpy
https://realpython.com/python-async-features/
https://realpython.com/async-io-python/
this is fucking me into brain for 4 days
i dont have th epatience anymore
async def Crispy(ctx):
async with aiohttp.ClientSession() as cs:
async with cs.get(urlCrispy) as resultsCrispy:
await resultsCrispy.text
a=resultsCrispy.text
docCrispy = BeautifulSoup(a, "html.parser")
await ctx.send(docCrispy)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object method can't be used in 'await' expression
can u just tell me
whats wrong
though calling a function is not really async related, it's basic syntax knowledge
ill leave server and never ask nother time for help
you're not calling the function
pls just ned the godamn suffe
how do you call a function in python ?
I'm literally telling you where you made a mistake
where
first of all, do you know what function I'm referring to?
the interpreter too
this is bringing me pain
the problem is await results.text
what should it be
you're not calling the function, you're referencing the function
yes
ok
don't forget the await
"and you gotta move it to the first argument of the BeautifulSoup class"
?
he's saying that the output returned by the function should be passed as first positional argument of BeautifulSoap obj
same error after resintalling python
that's not a python error
wrong ss
what you're doing in your code
RuntimeWarning: coroutine 'ClientResponse.read' was never awaited
self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
line 4 is the error
could you check what dpy version you're using?
have you tried to restart the ide?
yea]
you're not awaiting read
whats the command
pip freeze iirc and search for discord.py
1.73? i think
async def Crispy(ctx):
async with aiohttp.ClientSession() as cs:
async with cs.get(urlCrispy) as resultsCrispy:
await resultsCrispy.text()
docCrispy = BeautifulSoup(resultsCrispy, "html.parser")
await ctx.send(docCrispy)
print(discord.__version__) or pip show discord.py
yeah, you gotta update discord.py py -3 -m pip install -U discord.py
re run your code now
`
2022-09-22 16:40:24 INFO discord.client logging in using static token
Traceback (most recent call last):
File "C:\Users\User\Desktop\ELUSIVE-API\a.py", line 18, in <module>
client.run("my token")
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
return future.result()
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 746, in start
await self.connect(reconnect=reconnect)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 672, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
PS C:\Users\User\Desktop\ELUSIVE-API> ```
my actual token is there
Read the error
im blind Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
async def Crispy(ctx):
async with aiohttp.ClientSession() as cs:
async with cs.get(urlCrispy) as resultsCrispy:
await resultsCrispy.text()
docCrispy = BeautifulSoup(resultsCrispy, "html.parser")
await ctx.send(docCrispy)
you should store in a variable await resultsCrispy.text() and pass that variable as first positional argument of BeautifulSoap obj
fixed ty
you're welcome
@client.command()
async def Crispy(ctx):
async with aiohttp.ClientSession() as cs:
async with cs.get(urlCrispy) as resultsCrispy:
a = await resultsCrispy.text()
docCrispy = BeautifulSoup(a, "html.parser")
await ctx.send(docCrispy)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In content: Must be 4000 or fewer in length
you're trying to send a message that surpass the discord char limit
I think that error body was quite informative by the way
They are usually quite helpful to read
@commands.slash_command()
@discord.guild_only()
@commands.has_permissions(manage_messages = True)
async def nick(
self,
ctx: discord.ApplicationContext,
member: Option(discord.Member, "The user who's nickname you want to manage.", required = True, default = None),
*,
name: Option(str, "The new nickname of the user.", required = False, default = None)):
try:
await member.edit(nick = name, reason = default.responsible(ctx.author, "Changed by command"))
message = f"**{member.name}'s** nickname was edited to **{name}**."
if name is None:
message = f"**{member.name}'s** nickname was reset."
await ctx.respond(message)
except Exception as e:
await ctx.respond("An error occured, please contact support.")
print("An error occured with the nick command: " + str(e))
Why is my member option coming up as optional when I set it to required?
You set it to None by default
So no, it isn't required. If they don't provide it, it transforms into None
so what is it supposed to be by default?
No worries!
Yes but wrong channel
k sorry
how can I move a forum post from one channel to another in disnake?
async with aiohttp.ClientSession() as cs:
async with cs.get(url) as results:
a = await results.text()
doc = BeautifulSoup(a, "html.parser")
vallist = doc.find_all("span")
status=vallist[0]
await ctx.send(status)```
You shouldnt be opening a aiohttp session each time you invoke the command and you can always aiohttp.request so you dont nest context managers
!d aiohttp.request
async-with aiohttp.request(method, url, *, params=None, data=None, json=None, headers=None, cookies=None, auth=None, allow_redirects=True, max_redirects=10, encoding='utf-8', ...)```
Asynchronous context manager for performing an asynchronous HTTP request. Returns a [`ClientResponse`](https://aiohttp.readthedocs.io/en/stable/client_reference.html#aiohttp.ClientResponse "aiohttp.ClientResponse") response object.
if i dont
it doesnt work
?
if i dont put async with aiohttp.ClientSession() as cs:
async with cs.get(url) as results: ont the beginning it doesnt worl
Just use the function given?
wdym?
^
i am doing that?
Either way you should start a client session once and then use that session with aiohttp.ClientSession.request
its websraping
and it chnages constantly
That still doesnt have any effect on each HTTP request
then how should it look?
the code
snipes = dict()
def snipe_embed(context_channel, message, user):
if message.author not in message.guild.members or message.author.color == discord.Colour.default():
embed = discord.Embed(description = message.content, timestamp = message.created_at)
else:
embed = discord.Embed(description = message.content, timestamp = message.created_at)
embed.set_author(name = str(message.author), icon_url = message.author.avatar.url)
if message.attachments:
embed.add_field(name = 'Attachment(s)', value = '\n'.join([attachment.filename for attachment in message.attachments]) + '\n\nAttachment URLs are invalidated once the message is deleted.')
if message.channel != context_channel:
embed.set_footer(text = 'Sniped by: ' + str(user) + ' | in channel: #' + message.channel.name)
else:
embed.set_footer(text = 'Sniped by: ' + str(user))
return embed
class utility(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.snipes = {}
self.editsniped = {}
@commands.Cog.listener()
async def on_message_delete(self, message):
if message.guild and not message.author.bot:
try:
snipes[message.guild.id][message.channel.id] = message
except KeyError:
snipes[message.guild.id] = {message.channel.id: message}
@commands.command()
@commands.cooldown(1, 3, commands.BucketType.user)
@commands.guild_only()
async def snipe(self, ctx, channel: discord.TextChannel = None):
if not channel:
channel = ctx.channel
try:
sniped_message = snipes[ctx.guild.id][channel.id]
except KeyError:
await ctx.send("There's nothing to snipe!")
else:
await ctx.send(embed = snipe_embed(ctx.channel, sniped_message, ctx.author))
I need help.. my snipe command isn’t working & it doesn’t send an error either. @primal token
Just make an instance of aiohttp.ClientSession in something like setup_hook and use setattr to set an attribute of the newly made session and then you can use that
are there any good tutoriaals
on that
im loosing my mind with this
No, it's just code structures.
nice
How can i make it so the user has to say yes to continue?
!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**...
You can wait for a message event
Ahh thank you very much
i will try it out and see how it goes
Not sure what to input in the brackets though, is the client.command not an event though no?
How can i pass in a requirement for the words Yes or something?
Check the examples in the doc
Ty
I try run this make channel command but it returns no object for the id?
File "c:\Users\wayed\Desktop\MerchantBot\bot.py", line 76, in make_channel
channel = await guild.create_text_channel('secret', overwrites=overwrites)
i think its something to do with my overwrites?
why is this an error? do i need to import something? also this is a cog file idk if that matters
Solved, my bad it was accessing a role tht wasnt there due to my spelling mistake on the role
I am in a cog, the starboard group commands are not working, and there is no errors. Why is that
This is in a cog file do I need to import something or did i spell something wrong
the group doesn't exist
Please help, this is the code that I have
bot = commands.Bot(command_prefix=“.“)
It keeps returning this error
TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intent'
I’m not good with discord bots, and I’m still pretty new to python, and I just looked at some website to help me with this, please don’t judge
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
I would recommend you learn all the concepts that are used in Discord.py, heres a list of them with good resources:
#discord-bots message
Thanks
Ok
[2022-09-22 17:52:37] [INFO ] discord.client: logging in using static token
Traceback (most recent call last):
File "C:\Users\Travis\PycharmProjects\MainAttempts\PikleDiscordBot.py", line 28, in <module>
bot.run(DISCORD_TOKEN)
File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Users\Travis\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Travis\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
return future.result()
File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\client.py", line 745, in start
await self.login(token)
File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\client.py", line 577, in login
raise TypeError(f'expected token to be a str, received {token.__class__!r} instead')
TypeError: expected token to be a str, received <class 'NoneType'> instead ```
Now I’m getting this error
Your token must be a str
Guys is there any event in dpy that's gets triggered when my bot gets rate limited?
I have it like this
DISCORD_TOKEN = os.getenv(“insert token here”)
!d os.getenv
os.getenv(key, default=None)```
Return the value of the environment variable *key* if it exists, or *default* if it doesn’t. *key*, *default* and the result are str. Note that since [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") uses [`os.environ`](https://docs.python.org/3/library/os.html#os.environ "os.environ"), the mapping of [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") is similarly also captured on import, and the function may not reflect future environment changes.
On Unix, keys and values are decoded with [`sys.getfilesystemencoding()`](https://docs.python.org/3/library/sys.html#sys.getfilesystemencoding "sys.getfilesystemencoding") and `'surrogateescape'` error handler. Use [`os.getenvb()`](https://docs.python.org/3/library/os.html#os.getenvb "os.getenvb") if you would like to use a different encoding.
[Availability](https://docs.python.org/3/library/intro.html#availability): most flavors of Unix, Windows.
Traceback (most recent call last):
File "C:\Users\Travis\PycharmProjects\MainAttempts\PikleDiscordBot.py", line 28, in <module>
bot.run(DISCORD_TOKEN)
File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Users\Travis\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Travis\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
return future.result()
File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\client.py", line 745, in start
await self.login(token)
File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\client.py", line 577, in login
raise TypeError(f'expected token to be a str, received {token.__class__!r} instead')
TypeError: expected token to be a str, received <class 'NoneType'> instead ```
Still getting this
run [args ...]``````py
restart [args ...]```
Restart the debugged Python program. If an argument is supplied, it is split with [`shlex`](https://docs.python.org/3/library/shlex.html#module-shlex "shlex: Simple lexical analysis for Unix shell-like languages.") and the result is used as the new [`sys.argv`](https://docs.python.org/3/library/sys.html#sys.argv "sys.argv"). History, breakpoints, actions and debugger options are preserved. [`restart`](https://docs.python.org/3/library/pdb.html#pdbcommand-restart) is an alias for [`run`](https://docs.python.org/3/library/pdb.html#pdbcommand-run).
ImportError: cannot import name 'RequestsWebhookAdapter' from 'discord' (/home/container/.local/lib/python3.8/site-packages/discord/init.py)
fix?
i'm stupid can't help sorry
can you provide the full traceback of that error? sounds like another package might be conflicting with your discord package
thats the only thing it gives
I think it should give a bit more than that, but it does look like some other package is conflicting
why are you still using discord.py
im not spending my time to migrate over
it works, it works lmao
it's not that hard to migrate
or yeah that could have been it
iirc dpy 2.0 changed that aspect of webhooks (it's somewhere in the migration guide)
i found this good hosting, that only charges 1.50 a month
i use to host my bots on a raspberry pi
lmao, when you get mad clients that use your bot
you can't be using raspberry pi
ive had no issues with it
bit of a reach x)
tru tru lmao
just like i have other stuff on my server so transferring all of it would be a pain in the ass
you seem like you don’t like updating
i do freelance shit and most of my clients are from france
It would depend.
or neibhouring
so since ovh has pretty good servers there i never changed
until that incident when one of their data centers literally went on fire
all I can think of the word "plox" is
please -> pls -> plz -> pliz -> plix -> plox
That's trust issues right there
Do you have any feedback?
Is the thumbnail redundant?
same image 3 times, yes
Okay I remove.
https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32#slash-command-application-with-a-bot
so any way to put this command inside the class?
Wouldnt recommend it, It's better to have it in a modular ext over having it in your Bot subclass which may clutter the whole class's structure and will not have the benefits of something like reloading a commands state.
ok, but is it possible
Yes
You'll need to use self.tree.add_command or whatever the method is to register it
How can I reload a YAML file without having to restart the bot?
What do you mean reload a yaml file
Those are two very different things
If you want to just re-read the yaml file then just re-read the yaml file
How? I tried that and the bot just reads the cached old version anyway
How are you re-reading it?
Hang on
@commands.command(name='reload', hidden=True)
@commands.is_owner()
async def _reload(self, ctx, *, cog: str):
"""Command which Reloads a Module.
Remember to use dot path. e.g: cogs.owner"""
if cog == 'yaml':
await ctx.send('**`Reloading YAML file...`**')
try:
with open("/home/pi/Documents/Room_Sealer/groups.yaml", "r") as f:
self.bot.channelgroups = yaml.full_load(f)
await ctx.send('**`Reloaded YAML file`**')
except Exception as e:
await ctx.send(f'**`ERROR:`** {type(e).__name__} - {e}')```
@vocal snow
And what uses self.bot.channelgroups?
The main file
Can you share the code the uses it
@bot.command(name='seal')
@commands.guild_only()
async def _seal(ctx):
if ctx.channel.category_id in channelgroups['non-rp']:
await ctx.send(':x: | This command can only be used in rp!')
print(f'Command r!{ctx.command} used in a non-rp channel by {ctx.author.name}')
elif ctx.channel.category_id == 741756076126634076:
await ctx.message.delete()
await ctx.send('(Wrong command! `r!rp-set-seal` or `r!rp-set-unseal` is the correct ones to use)', delete_after=7)
print(f'Command r!{ctx.command} used in a general rp channel by {ctx.author.name}')
elif ctx.channel.category_id in channelgroups['ships']:
await ctx.message.delete()
await ctx.send('(Ships cannot be sealed by the bot. Use [#741756142916468868](/guild/267624335836053506/channel/741756142916468868/), [#747578010278035536](/guild/267624335836053506/channel/747578010278035536/), [#741756219064189029](/guild/267624335836053506/channel/741756219064189029/), [#745682027667390505](/guild/267624335836053506/channel/745682027667390505/), or [#741756303814426768](/guild/267624335836053506/channel/741756303814426768/).)', delete_after=7)
print(f'Command r!{ctx.command} used in a ship channel by {ctx.author.name}')```
well yes
Ok, I'll make the fix when I wake up
Not sure what youre trying to do exactly but i do feel that this should addressed, with open will block the event loop as its not scheduling the task of a function, it's not really an issue as it wont block the event loop for much time but it's good practice to open a file asynchronously so you dont face any weird behaviors or speed related issues.
It's never going to be on a task
Thanks
you can definitely rephrase this to be less confusing i think
I didnt ment it as a Task object, but an actual job a function may carry
Noted
Fixed minor issues, it should be readable for someone with knowledge of asyncio
yep still pretty bad wording there
Can you please enlighten me?
here'a a simpler explanation: open() is a blocking IO call, you should probably use an async variant of the function to avoid blocking the event loop.
as its not scheduling the task of a function
what does this even mean?
"as its not scheduling the task of a function" what that even eman xdd
I ment, not scheduling a function to the event loop, which the wording issue occurred upon an edit i made
you don't schedule a function to the event loop...
If you want to a TL;DR, sure
a coroutine!
your explanation is simply too long, it can be shortened without losing information.
What?
given your statement i assumed you would have a technical understanding too
A coroutine can be a generator, yes, but i was just correcting myself so i dont know what's your point?
a coroutine object is not a function (or callable, for a better term)
a coroutine is a generator (subclass)
this is my point
https://github.com/python/cpython/blob/main/Objects/genobject.c#L1170
if you want to read the source for coroutine
What do you mean exactly by
you don't schedule a function to the event loop...
?
I may have worded it incorrectly but i did correct myself

AFAIK when you have blocking code the connection on between the Bot and discord websocket receives a delay, this delay accumulates until the Bot disconnects from the websocket due to the delay, if the library you are using implements a resume logic then the library will try to reconnect.
Events dispatched between the resume operation are lost, your Bot will not receive them, instead when the bot is behind the discord websocket the bot will perform the functions associated with event dispatches delayed
if the resume start on (bot blocked) it should receives a, b, e
btw the bot doesn't do resume when it's blocked, it'll try to resume the session when it's disconnected from the discord ws
the delay between discord ws and your Bot leave some messages sent by Discord unanswered, or rather, the replies your Bot sends them late, sometimes too late and then discord will disconnect your Bot thinking it is dead
that’s no good... you should avoid doing that or just don’t use an async library
can you give an example of what you’re trying to do that causes ur bot to enter this blocked state?
yep, you should use asyncio’s networking implementation
hm
what is “Stream”?
you use await reader.read(...)
well yeah i know what you mean now
Bot B receives data, so how it can't know? that depends on how Bot B dispatch custom events
referring to it as “Stream” is way too vague
yes, you can use loop.create_task()
i mean a little context would be nice, “asyncio streams” makes more sense to me
yep
asyncio.get_running_loop() should be sufficient
assuming you’re using client.run() in discord.py
i mean you can read the source for yourself if you want
and this is how the on_message event is dispatched, for example
self.dispatch is a bound Client.dispatch method
discord.py internals are pretty terrible, trying to read it is a nightmare
👍
http.py is one of the most hellish file
The whole codebase should be restructured
Guys is there any event in dpy that gets triggered when bot gets rate limited?
The errors start coming up, you may get them in on_error method of commands.Bot that's for sure
Because it might occur in listeners, on_command_error is not really suitable
on_error is event?
It's a method of commands.Bot as I said
bot.on_error?
Take a look at this https://github.com/Exenifix/AIAS/blob/master/utils/bot.py#L106-L108
utils/bot.py lines 106 to 108
async def on_error(self, event_method: str, *args, **kwargs):
self.log.error("Unhandled exception occured at %s", event_method)
await self.log_error()```
So i put this in my bot subclass?
I mean the on_error method
all of it's bad imo
lol i mean if you think http.py is bad, you haven't seen the commands extension
or state.py
or gateway.py
honestly at this point i'm gonna start listing out all the files
check ext.commands.core.py
most wtf thing to ever exist
@vale wing it not worked
async def on_error():
print("rate limited")
os.system("kill 1")
The on_error has arguments
And the error is not necessary the HTTPException with 429 code
!d sys.exc_info you get the exception itself via this
sys.exc_info()```
This function returns a tuple of three values that give information about the exception that is currently being handled. The information returned is specific both to the current thread and to the current stack frame. If the current stack frame is not handling an exception, the information is taken from the calling stack frame, or its caller, and so on until a stack frame is found that is handling an exception. Here, “handling an exception” is defined as “executing an except clause.” For any stack frame, only information about the exception being currently handled is accessible.
Also about this, I'm not sure what exactly kill 1 does in replit, but it seems like it kills the running process, which means your bot will shutdown. You might want to use shell script to restart the bot instead
how to save my 8ball command responce in cache that the response of a question never changes.
then if u ask a same question to the bot again and again it should always give the same answer
Ye how to?
Just use a dict
Have you tried googling
#bot-commands
No
You should
Bruh?
That's a helpful skill for a programmer
Ok
I need one help
how to restart my bot?
Personally I'd do it with shell script
if you want the responses to be same throughout, you'd have to use a database
but it's impl with cache could be with a dict
I can't understand cache and can't find a good documentation to learn about it
The cache is just a volatile type memory, it is handled by the processor of the machine
When we say that a data is stored in the cache it means that in that specific instance of a process you can access that data
When you declare a variable for example, it is not allocated in the memory permanently, the portion of memory that needed to be stored by a variable will be allocated only during the runtime of your program. Once the program finish the data will not physically exist anymore
So to do that, you only need to create a dict inside of your program, accessible everywhere in your code, and the trick is done 
you don't have to say all that
He was confused about what is the cache, we're here to help people learn. I've just explained him how cache and runtime memory works, those things are not useless as they appear
you were talking about the low-level cache
the very low-level one
you could've just said "make a dict and set it to the first response of that question"
Ashley told to him and he didn't understand 
That means that he needed an explanation 
well i would say is the most useful skill for a programmer 
So basically you save stuff somewhere not to fetch/generate it every time
hmm okay... like it will store and save a output to save computing if the output in needed again?
Yes like that
cache ( in discord.py ) are just dictionaries which saves IDs and objects as key-value pairs
for example guilds are stored like this ```py
guilds = {guild_id: guild_object}
when you use get_guild, get_member etc, dict.get is called for those objs
For example you want a set of records from database with very complex condition, large database and small amount of records you actually need, you can just fetch them once from database and use
how to store them in cache now?
Although in case of database you might need to do the data syncing properly, this is not your case
the dictionary is the cache itself
you store it using dictionary[key] = value
and whenever you need the results you can do ```py
dictionary [key] # raises an error if key is not in dictionary
or
dictionary.get(key) # returns None if key is not in dictionary
eball_data = {}
@bot.command(aliases=["8ball", "8balls", "eb"])
async def eball(ctx, question:str):
random_reply = random.choice(r8ball)
if question in eball_data:
await ctx.send(eball_data[question])
else:
eball_data[question] = random_reply
await ctx.send(eball_data[question])
so u mean this is okay?
and btw it works
yep seems fine to me
can a key contain more that one value?
nope, but you can store all sort of data types in the value, even lists, sets, tuple or another dict
this info is going to change my whole life ☠️
not possible but the solutions suggested by blvck can be used
you could store a tuple or list
how to acsess "name" stored in a list called "pokemon_data" with is the value of the key called "pokemon"?
lists dont have key-calue pairs? unless the list contains a dict
value*
💃 that's what he said
@slate swan then how to solve this?
what does the structure look like
I have a dict named "pokemon". I have a key in "pokemon" named "pokemon1" whole value should be "name" stored in another dict named "pokemon1_data"
nope i still haven't got it yet 
bruh bruh
so you mean you have this for example
I have it for irl
pokemon = {"pikachu": {"name": "pikachu", "type": "electro", "moves": ["thunder", "quick attack", "electro ball", "double team"]}, ...}
```?
Anybody ever worked with music bots?
Yes and it wasn't a pleasant experience
Were you able to get your music bot to play music from a youtube url
i did 👀
Without downloading the file?
Can you send the code? I give up on trying to google solutions. everythings all wrong, not even the discordpy example works
well yeah downloaded but not saving locally ig idr
ytdl 😅
i used ytdl and ffmpeg before it was banned 👀
Guys how i can use local image in the embed?
So is it still possible to make a music bot?
use SoundCloud ig
Pls help anyone
how would you add cooldowns for slash commands in nextcord??
wassup, is this how i make a function run once an hour, to allow bot commands to work meanwhile
async def checkUserExists(userID):
while True:
asyncio.sleep(3600)
runFunc()
!d discord.ext.tasks.loop this
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
which lib?
ok thanks
dpy
put the url as
url="attachment://image_name.ext"```
Ok
it is if it doesnt get verified
or in certain circumstances, it could get banned even if it id private, but it wont most prolly
What can I do if the content it wants to send is to big is there a way to split it into more than 1 Message and then send those
send as a txt file
does this seem right```py
@discord.ext.tasks.loop(hours=1, reconnect=True)
async def compareUpdates(ctx):
runFunc()
If you need ctx in it, ye
Then don't pass ctx in the parameter
ight thanks
;D
https://discord.com/api/v{version_number}
You can look at the references
https://discord.com/developers/docs/reference
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Thankss
So I was in the callback of a view, and I tried to do interaction.edit_original_message(...), but then I got an Invalid Webhook error, any idea why?
how do u install requirements again
sadly youtube_dl is not for discord bots now
😦
Can you send the traceback?
interaction expired, non deferred interactions lasts 3 sec, deferred ones 15 min
How to defer it?
iirc for d.py should be interaction.response.defer()
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
Guys do we need application.commands scope to make slash commands work?
Yes
Yes ofc
why doesn’t bot.tree.command work
AttributeError: 'SlashBot' object has no attribute 'tree'
it gives me this error
You have to pass the overwrite as nextcord.PermissionOverwrite not dictionary
overwrite = nextcord.PermissionOverwrite(...)
await c.set_permissions(member, overwrite=overwrite)
await c.set_permissions(ctx.guild.default_role, overwrite=overwrite)
await c.set_permissions(ctx.guild.me, overwrite=overwrite)
If you want to set the overwrite for multiple roles or members, you have to set it individually
Guys how can I make a system that when my bot gets rate limited it types kill 1 in the shell?
Easy don't use repl
!d os.system use this
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").
how can i disable command in a pertucular server ?
i dont think command.update(enabled=False) will work it will disable for all 😳
I mean it do this when bot gets rate limited
Is there any event for it?
You need a command check that would prevent it from running in disabled server
I already told you, didn't I
and for check i have to store data in db ?
damn
As you wish
any other option ?
If it is long-term storage there's no other option
If you don't want it to be persistent between bot runs then just put it into some dict
I was not able to understand sorry
When you shutdown the bot just os.system("kill 1") is most likely gonna kill the bot itself and no other instructions will continue, so you need to either use the shell script so all the commands you need get executed correctly, or something like kill 1 && python3 main.py
But the most simple thing to do to accomplish this is basically don't fricking use replit
I don't have computer or laptop sorry 😔
Bro but how will it get triggered?
why would there be an event for "you can't get events anymore"
Means it have no solution?
Idk how to use it
just download your files, pip install the requirements
and use python filename.py
*i don't know how to use it
a link is always clickable wdym
there was this one time yesterday, i my bot sent a valid link that if copy pasted into google was valid but the link itself wasnt clickable
i cant recreate it right now
ah wait, i think i figured it out nevermind
you probably forgot to add http/https
Subclass the commands.Bot and override on_error method, then get exception via _, error, _ = sys.exc_info() and check if error is an instance of HTTPException with 429 code
I don't know how to explain it any clearer without spoonfeeding
overriding on_error can be very risky, make sure you don't end up eating other errors
Yeah make sure to always print the traceback
And yeah the traceback object is the third value in tuple returned by exc_info
@client.listen()
async def on_guild_join( guild):
await db.create_collection(name= str(guild.id))
async def on_message(message):
if message.author == client:
await message.channel.send(client)
return
if message.content == 'ok':
await message.channel.send('Hello World!')```
why this not working ?
any idea
You didn't register the on_message event
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
(main.py)
@bot.command()
async def usluga(ctx):
view = ticket()
embed=disnake.Embed(title="Zamów usługę :bell:", description="Wybierz kategorię usługi, która Cię interesuje", color=0xae00ff)
await ctx.channel.send(embed=embed, view=view)```
(cogs--->ticketSystem.py)
what's problem
ye xd
Your view has the same name as your cog and is being overwritten
so how can i fix it?
???
anyone used asyncpg
its recommended in a discord.py github post for background tasks
but apparently i need to add a C compiler, unless if i have a recent pip version, which i do, import could not be resolved persists
https://magicstack.github.io/asyncpg/current/installation.html
or is this useless anyway, what i do is that each hour it does webscraping and compares it to whats in the db
Can anyone help me with my bot verification?
??what kind of verification
I want verify my bot, it's asking for a tos and i need help for it
Huh ...maybe a screenshot of the error will help
It's not an error
Question:
How can i check for a message in a normal command like this and than print it?
return message.author == ctx.author and message.channel == ctx.channel and message.content.lower() == message```
Just pip install asyncpg works fine on all systems
You need C compiler only to build it from source
print before returning something, also ctx is not defined, and what's the point of message.content.lower() == message ? this will return false
i did, still acts as if there wasnt the library
importing it is like i didnt install it
i removed it and tried again too
Are you sure you install it into the correct environment and run the script from the same environment
i dont use venv, i did it from the vs code terminal
How many python versions do you have installed
no idea lol
all i know is that python isnt a command, so i guess i have just python 3
i have 3.10.5 for py3
ok well thanks
Using venvs is a good practice and helps to avoid these cringe PATH issues
Create a venv via python3 -m venv venv and select the new interpreter from command pallet (CTRL + SHIFT + P -> Select Interpreter)
the i cant access the library elsewhere
ight then
When you install many global packages they might start having dependencies conflicts
So better to have everything isolated
hey anyone able to help me make my first discord bot?
i see what u mean
tho ive been using them for 1 proj so far
then i gotta remove them for future stuff
As for your case, you most likely have several python versions installed, and you pip install with one, but run the script with another
Venvs help to avoid that too
ok, thanks
!dashmpip
When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.
Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.
Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.
what is num_range
i got the locked error from sqlite3
should i consider a diff db, or is it ight to make one connection like this and use it over time
also, if I do that, do i set the cursor each time and close it?```py
@bot.event
async def on_ready():
if bot.db_con is None:
bot.db_con = bot.db_con = await aiosqlite.connect("database.db")
whats the code so no one can DM my discord bot? and where do i put it.
whats the code so no one can DM my discord bot? and where do i put it.
idk, why would u worry ab that
People can DM you but you can choose to ignore it
i said my bot
I know, same deal with your bot
iirc you can just not set the dm unprivaliged intent
because i have an Premium version of my bot that i dont want people to DM the commands to. It defeets the whaol thing that instead of getting premium thay just use it inside of DM's
Just ignore DM channel messages in your on message with conditional process commands
A check would be enough
BROOOOOOOOOO
idc about what u guys say, can you just tell me the code
i have been looking EVERYWHERE
we said u can make a check on message
guys hwo have code that give user a a role for set time
make a task that removes it
the server is about this predictions bots, i want the script so thay will type commands in chat and be active. it defeets the whaol ting if i have a dead chat and thay are in bots dm
so like a task loop or cog
idk how to do that, please tell me
how?
then u check if the user has premium
to see if u allow them to use commands
so u search in ur database
cause u obviously use one for remembering who has premium
Why make unnecessary references?
bruh
kek
this was supposedly a solution to the locked error
but i still get it, am i supposed to create a cursor and close it each time? (i do btw)
(https://stackoverflow.com/questions/73416313/whats-making-this-code-lock-my-aiosqlite-database)
My discord.py bot handles data inputs (invites, bans, warns, etc.) and inserts them into an aiosqlite database. An error is raised:
OperationalError: database is locked.
Multiple commands work in
how to set that
like
Prefix for your server is -----
in bot for custom server prefix
Those comments arent correct and you can always set a max concurrency
oops sorry its node.js
no, i just anyone know how to close dms for a bot?
Sir this is a python server
yh they mentioned i can increase the timout for lock or whatever, but couldnt find online, do u know?
or making 1 con forever is ight
Why are you making an instance of Intents but not using it?
Hey guys! So i want to know that i want to make an command that tells you howmuch time your bot has been on. could someone help me?.
just store the time when your bot starts
How do you do that.
No , I want it by a script.
yes, i wanna remove the dm thing
its not mine, i wanna have it like he does
using time.time()
Well i dont want it like that.
I want it that it calculates by its self when using an command .info
in a variable most likely
or database
just store the current time when the bot starts and when .info command is used then from current time again subtract the time you stored
Thanks.
it's better to store the time inside of on_connect if your bot isnt HTTP only and bind the value to the instance of your bot
oh, I forgot about on_connect completely

anyone knows a simple easy way to make an eval command ?
You can use snekbox:
https://github.com/python-discord/snekbox
ok
That's what @unkempt canyon uses!
ok
ok
ok
👌
I just pushed this and I'm getting the same results. New categories added to the yaml file are not being recognized by the bot after an attempted reload
Hi
so how do i make a command ?
!src eval
Run Python code and get the results.
You can use this one as guidance so you can implement it yourself
k ty
@bot.command, @client.command or @commands.command
It would depend
On where you're doing it and how your previous lines of code are written
It would depend on your codebase and its structure, yes.
Btw, @primal token do you by chance know of a way to store info like category IDs into a file and have that file be reloaded easily via a command for if statements?
You can use json with aiofiles or you can also use a container object
Code:
import ast
def insert_returns(body):
# insert return stmt if the last expression is a expression statement
if isinstance(body[-1], ast.Expr):
body[-1] = ast.Return(body[-1].value)
ast.fix_missing_locations(body[-1])
# for if statements, we insert returns into the body and the orelse
if isinstance(body[-1], ast.If):
insert_returns(body[-1].body)
insert_returns(body[-1].orelse)
# for with blocks, again we insert returns into the body
if isinstance(body[-1], ast.With):
insert_returns(body[-1].body)
@bot.command()
async def eval_fn(ctx, *, cmd):
fn_name = "_eval_expr"
cmd = cmd.strip("` ")
# add a layer of indentation
cmd = "\n".join(f" {i}" for i in cmd.splitlines())
# wrap in async def body
body = f"async def {fn_name}():\n{cmd}"
parsed = ast.parse(body)
body = parsed.body[0].body
insert_returns(body)
env = {
'bot': ctx.bot,
'discord': discord,
'commands': commands,
'ctx': ctx,
'__import__': __import__
}
exec(compile(parsed, filename="<ast>", mode="exec"), env)
result = (await eval(f"{fn_name}()", env))
await ctx.send(result)```
**Error:**
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
You mind DMing me how aiofiles work?
!pypi aiofiles | it's a library that manages files asynchronously
pls help
I have a problem with this code it says smth about empty message
? how
?
Whenever i run this command to create a private channel, it ends up looping infinitely ?
@client.command()
async def make_channel(ctx):
guild = ctx.guild
member = ctx.author
admin_role = get(guild.roles, name="Admin")
channelname = 'Seceret'
mbed = discord.Embed(
title = 'Success',
description = "{} has been successfully created.".format(channelname)
)
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
member: discord.PermissionOverwrite(read_messages=True),
admin_role: discord.PermissionOverwrite(read_messages=True)
}
channel = await guild.create_text_channel(name='{}'.format(channelname), overwrites=overwrites)
await ctx.send(embed=mbed)
test1 = await channel.send(embed=await make_channel(ctx))
await channel.send(embed=await IndicatorSale(ctx))
await test1.add_reaction(NReact)```
quite limited tho, it locks easily
async def make_channel(ctx):
guild = ctx.guild
member = ctx.author
channelname = 'Seceret'
mbed = discord.Embed(
title = 'Success',
description = "{} has been successfully created.".format(channelname)
)
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
member: discord.PermissionOverwrite(read_messages=True),
}
await guild.create_text_channel(name='{}'.format(channelname), overwrites=overwrites)
await ctx.send(embed=mbed)````might be a little bit different but the problem was in the (channel = await guild.create....)
Yes thank you very much
np 🙂
i saw my silly mistake, i was basically embedding the same channel made lol