#discord-bots
1 messages · Page 139 of 1
so at first he sees 0
side note: instead of py warnnum = 0 for table in data: warnnum += 1 you can do ```py
for warnum, table in enumerate(data, start=1):
oh
thats a way too
what should the warns command do?
yeah, and it counts the amount of previous warnings in the db?
tell me the whole logic of your warns command and how it's connected to your db, I'll wait
example
my warns command warns a member with a given reason
first it checks the db if he doesn't have more than x warnings already
if he does, kick, if he doesn't add the warning with the reason to the db and send a message...
when a user do smt a staff member can warn him, it doesnt really effect anything but a staff member can check warns of a member with the warns command (the one i have problems with) and kick or anything now for the backend the db should check if the user has warning and can use unwarn command and same w the check warns command they can check from the db
so, show me your code again
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
alright, first issue here is that you're using on_ready for api calls etc, you should use startup tasks
but that's not the issue here
so the warns command should only check the warnings a certain member has?
yes
alright, now we're getting somewhere
🙂
yes
('No reason provided', 1668948772)
alright, so you get a tuple returned
so table[1] should work fine, you don't need to int() that, since it's already an int
try and see
okaay
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'int' object is not subscriptable
whenever you send those kind of lines
I always want to see full traceback and also your current code in that command from now on
oh okay
preferably with a note where that line is
since I can't see line numbers in codeblocks on discord
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 165, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 96, in warns
em.add_field(name=f"Warning {warnnum}", value=f"Reason: {table[0]} | Date: <t:{table[1]}:F>")
TypeError: 'int' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 605, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1382, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 948, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 174, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'int' object is not subscriptable```
``` em.add_field(name=f"Warning {warnnum}", value=f"Reason: {table[0]} | Date: <t:{table[1]}:F>")
line 96
you printed data above that, right?
can you do cursor.fetchall() instead of fetchone()?
oh yeah
check if that changes anything
alr, there's multiple other optimization issues with that code, but Ig that's not your main issue
yep!
your main optimization would be to not use on_ready for changing your presence and starting your db
oh
thats also good
bot = discord.Bot(intents=intents)
AttributeError: module 'discord' has no attribute 'Bot' help
bot = discord.Bot(intents=intents)
AttributeError: module 'discord' has no attribute 'Bot'
``` can someone help me? i've been strugling on this error for like 30 mins...
You are following a py-cord tutorial, it's discord.ext.commands.Bot
💀
Someone grabbed my discord token cause they thought it was malicious i need help to prevent this from happening(the closest thing that my discord bot has to malicious is deleting messages that have bad words)
don't leak your token then?
I didn't
apparently you did, because someone uploaded it to github so it would get automatically invalidated for you
its not what your bot has since the token can be used to authorise requests to discord api it can do whatever is possible with the API
Hey guys
who would be able to make me a discord bot with just 1 "application command" so i can get the developer badge for $10 paypal
!rule 9
I'd die about the ten dollars
💀 10 dollars for a badge
which badge though
lmao
why not?
I dunno discord is bad
is there other requirements?
i alrdy have a bot but its developed in old asf python
and they didnt update that api im pretty sure
and it doesnt have any application commands lmao
Your bots slash command needs to be executed in the last 30 days I believe
made it like 3 years ago
That's the only requirement
yep thats fine
Your app is missing an invite link. Add one so users can add your bot to their server easily.
where the hell do i add this lmao
is there any easy way to check how many servers my discord bot is in?
do you know any alternatives to replit?
none that are free
how is replit related to a token theft....
A bot that plays music from youtube is no longer allowed even if its only in my server?
You could still make a bot play music but it would breach youtube's TOS at the same time too
default_role is everyone ?
So, if I want to keep my account alive its a no
yup
thanks
:)
not that youtube cares much lmao
and discord?
discord music bots were based on the fact that they used youtube_dl
so the popular music bots you see, most of them still use youtube_dl
The badge is not worth $10
does anyone have ideas to what i can add to my public bot?
Not even worth your time
i rlly dont know
Hi I have a noob question
I have all my commands in a one main.py file
Would it make much difference if i carry on like this rather than adding them to cogs ( i still have no idea how to do it )? Would it make it faster or it’s just more organized
It's more organized
Okay thankss
I don't have any bot running on v2, so there's that
the active developer badge required less efforts than a hypesquad badge to claim kek
you have
nah its more effort
im lazy to open vs code and create a bot app 😩
;-; i already had enough bots with app commands to claim one within an hour of release
how do u even get the badge?
what's the best way to organize cogs
a cog for one command? one cog for a command category?
Commands that belong together.
what if one command is not related to any
example? there is always a category it belongs to like economy /game/ moderation/ ||nsfw||
like a category with one command
will splitting to file per command affect the performance?
it'll just look messy
discord canary
Uh
create a category called miscellaneous/misc for such commands
k
I have a parameter called colour and a variable called yellow. This code:
if yellow==colour:
await guild.create_role(name=f'{name}', color=yellow)```
doesnt work and the issue is in the `if`. Why?
What i want to do is if the yellow is the colour parameter, to create a role with yellow color
what is your yellow variable? and how do you parse the colour var
discord mobile as usual
Can anyone tell me why I can't download the pip command?
try python -m pip if it still shows error you can install pip manually
my commands don't run ! i don't have a on_message event
is it possible it's for a while loop in the on_ready event ?
I have a group that's just called fun or utils
whats up with the pfp
its uglier than the old one
old one is making u a chad
I like to switch it up after a year or 2
k
Do you have message content intents enabled in both your dashboard and in your code?
error: subprocess-exited-with-error
exit code: 1
╰─> [126 lines of output]
error: legacy-install-failure
This is an issue with the package mentioned above, not pip.
hint: See above for output from the failu
Guys, I'm typing pip Install disco.py and it gives an error
i removed the while loop , and it was fixed
!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.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
seems like broken python install, it was just a Literal use
how do I fix it?
reinstall python, when did you install python 3.10?
could someone help me with this error please?
0|Runa | ret = await coro(*args, **kwargs)
0|Runa | File "/home/Runa/bot/cogs/giveaway.py", line 118, in giveaway
0|Runa | if time == -1:
0|Runa | TypeError: convert() takes 1 positional argument but 2 were given
0|Runa |
0|Runa | The above exception was the direct cause of the following exception:
0|Runa |
0|Runa | Traceback (most recent call last):
0|Runa | File "/usr/local/lib/python3.8/dist-packages/nextcord/ext/commands/bot.py", line 1382, in invoke
0|Runa | await ctx.command.invoke(ctx)
0|Runa | File "/usr/local/lib/python3.8/dist-packages/nextcord/ext/commands/core.py", line 948, in invoke
0|Runa | await injected(*ctx.args, **ctx.kwargs)
0|Runa | File "/usr/local/lib/python3.8/dist-packages/nextcord/ext/commands/core.py", line 174, in wrapped
0|Runa | raise CommandInvokeError(exc) from exc
0|Runa | nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: convert() takes 1 positional argument but 2 were given
code:
#convert time into something typable
def convert(time):
pos = ["s","m","h","d"]
time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d": 3600*24}
unit = time[-1]
if unit not in pos:
return -1
try:
val = int(time[:-1])
except:
return -2
return val * time_dict[unit]
#giveaway command
@commands.command()
@commands.has_permissions(kick_members=True)
async def giveaway(self,ctx):
await ctx.send("Let's start with this giveaway! Answer these questions within 15 seconds!")
questions = ["Which channel should it be hosted in?", "What should be the duration of the giveaway? (s|m|h|d)", "What is the prize of the giveaway?"]
answers = []
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
for i in questions:
await ctx.send(i)
try:
msg = await self.bot.wait_for('message', timeout=15.0, check=check)
except asyncio.TimeoutError:
await ctx.send('You didn\'t answer in time, please be quicker next time!')
return
else:
answers.append(msg.content)
try:
c_id = int(answers[0][2:-1])
except:
await ctx.send(f"You didn't mention a channel properly. Do it like this {ctx.channel.mention} next time.")
return
channel = self.bot.get_channel(c_id)
time = self.convert(answers[1])
if time == -1:
await ctx.send(f"You didn't answer with a proper unit. Use (s|m|h|d) next time!")
return
elif time == -2:
await ctx.send(f"The time just be an integer. Please enter an integer next time.")
return
prize = answers[2]
await ctx.send(f"The giveaway will be in {channel.mention} and will last {answers[1]} seconds!")
embed = nextcord.Embed(title = "Giveaway!", description = f"{prize}", color = ctx.author.color)
embed.add_field(name = "Hosted by:", value = ctx.author.mention)
embed.set_footer(text = f"Ends {answers[1]} from now!")
my_msg = await channel.send(embed = embed)
await my_msg.add_reaction("🎉")
await asyncio.sleep(time)
new_msg = await channel.fetch_message(my_msg.id)
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(self.bot.user))
winner = random.choice(users)
await channel.send(f"Congratulations! {winner.mention} won the prize: {prize}!")
val = int(time[:-1]) thats on a list
not a single item, here you're splicing not indexing
unless its a string?
oops wrong area hold on
oh wait, nevermind! i added self as a parameter to convert() and it seems to be fixed
yeah doesnt look like its in a class
thank you so much though
however you can make discord bots in a class lol
yeye
how do i get a timestamp for "in 24 hours"
await channel.send(f"Restart in {24 hour timestamp}")
Could use some help in #help-bagel
my friend you should learn the basics of programming
i am the type that old/young doesn't matter
😳
i have no comment...
does anyone know how to pull old usernames?
Still need help
where is the issue?
Resolved
Hello! How do I handle optional args? I am trying to make it so if there is no argument, (if arg is None) it does one thing or else does another.
I have before the arg so *arg and have it so if arg is None: and then an else statement, but it does not seem to be working.
I am using discord.py
@sick birch you think you can please help? 🙂
send code
code
Not home anymore lol 😦
@bot.command()
async def test(ctx,*,arg=None):
if arg is None:
do_something()
else:
do_something_else()
you can do something like that
and done need to ping the staff's etc, just ask 🙂
My bad
So the * makes the next arg optional?
Why not *arg
Hello, is it possible for discord bot to?
- Find certain image from the inventory - screenshot upload to the bot
- Detect the quantity of the item
- Detect the price, and show the price based on the quantity
- Total all the assets in the inventory
everything is possible on internet bro
Well good to know then
arg=None give a default value
yea its possible, now i read it all
Time to start from the base.
What "inventory" are you referring to?
Basically inventory from a game, let me screenshot example of the inventory
The plan was to detect the amount of the item in the inventory and then it tell you the total price for it. Something like that
Not sure if that works or not, It just for test.
the numbers can be figured out easily but differentiating between blocks and telling them apart will be tough and kinda complex
Yeah, that's what I'm thinking.
most probable way is to identify is based on colour u will prolly need opencv but operations like this will prolly be resource consuming not economical for a discord bot
Well this main question was in general chat but it just ignored so I asked in here.
Anyways, I already done half of this so no worries.
So what’s the * for before?
in general python * indicates following arg as a kwarg but in dpy its basically indicates the next arg to be a greedy arg and consume everything passed in the function from that param onwards
Ah so like if I wrote a sentence it would take the entire sentence as that one arg?
indeed
i have done something like that before
Oh? That's interesting
{
"image_url": "1253",
"image_url": "6346",
"image_url": "8615"
}
i have story the items in json file like that (image_url must be the key because is unique (cant have 2 records with same key)
after that using PIL i take this data and return it to inventory items with amount ! (key for image_url and value for amount)
you can create and pages if you have many items!
What if it’s just *arg? What’s a kwarg?
*arg is a similar consumer and it consumes all positional arguments there on
keyword argument
@nextcord.ui.button(label=":newspaper:", custom_id="paper")
async def paper(self, button:nextcord.ui.Button, interaction: nextcord.Interaction):
if not interaction.user:
return await interaction.response.send_message(content="Thats not your button!", ephemeral=True)
if interaction.user:
return await interaction.response.send_message(content="Choosed paper.", ephemeral=True)
await interaction.response.send_message(view=rpsView())```
when another user that didnt start the rps game tapping on the button it doesnt response Thats not your button! its saying Choosed paper.
w no error
interaction.user is the user who press the button
so what are you checking for? xd?
so how do i take the one who did the command
are you inside a view?
yes
show me your command that call the paper view
so you can pass the interaction of the command when you send the first response to the slash command
the __init__ of your view subclass should accept an argument such as (for example) original_interaction and save it as class variable (self.original_interaction = original_interaction) the only thing you will have to do is pass the original interaction when creating the object of your custom view
await interaction.response.send_message(view=MyView(interaction))
omg thank you so much!!
@nextcord.ui.button(label="📰", custom_id="paper")
async def paper(self, button:nextcord.ui.Button, interaction: nextcord.Interaction):
if interaction.user:
return await interaction.response.send_message(content="Choosed paper.", ephemeral=True)
await interaction.response.send_message(view=rpsView())
oh okay
Another way could be to get the original message but in the way I sent you'll save a useless API call
@bot.command()
async def rps(ctx):
view = rpsView()
em = nextcord.Embed(title=f"Rps Game", description="Choose one of these options. \n :newspaper: Paper\n:new_moon: Rock\n:scissors: Scissors", color=0xfff8b0)
await ctx.send(embed=em, view=view)```
thank you so much u helped a lot!
@bot.command()
async def rps(ctx):
view = rpsView()
em = nextcord.Embed(title=f"Rps Game", description="Choose one of these options. \n :newspaper: Paper\n:new_moon: Rock\n:scissors: Scissors", color=0xfff8b0)
await ctx.send(embed=em, view=view(ctx.author))
oh
you gonna pass the ctx.author (the user who can use the interaction)
you will define the user in your button class
like self.author=author
and then do the check
if interaction.user == self.author
I would pass the entire ctx object so that in its class he can access what he wants without problems

Also it would be better to use ids, names and tags can change
ill try
can you show me the button class?
show me your button class!
class rpsView(nextcord.ui.View):
def __init__(self, author):
super().__init__(timeout=None)
self.author=author```
class rpsView(nextcord.ui.View):
def __init__(self, author:discord.Member):
super().__init__(timeout=None)
self.author=author
@nextcord.ui.button(label=":newspaper:", custom_id="paper")
async def paper(self, button:nextcord.ui.Button, interaction: nextcord.Interaction):
if interaction.user == self.author:
await interaction.response.send_message(content="Choosed paper.", ephemeral=True,view=rpsView())
oh i did return await interaction.response.send_message(content="Choosed paper.", ephemeral=True) await interaction.response.send_message(view=rpsView(interaction))
let me test it
no you need to initialize the view in your command body
@bot.command()
async def rps(ctx):
view = rpsView(ctx)
em = nextcord.Embed(title=f"Rps Game", description="Choose one of these options. \n :newspaper: Paper\n:new_moon: Rock\n:scissors: Scissors", color=0xfff8b0)
await ctx.send(embed=em, view=view)```
without ctx.author
also compare ids not names
^
i will change it later okay
ctx.author its not name
username + tag
me too 😢
it work?
you're welcome
i fixed it
#Button Class
class rpsView(discord.ui.View):
def __init__(self, author:discord.Member):
super().__init__(timeout=None)
self.author=author
@discord.ui.button(label=":newspaper:", custom_id="paper")
async def paper(self, interaction: discord.Interaction, button: discord.ui.Button):
if interaction.user == self.author:
await interaction.response.send_message(content="Choosed paper.", ephemeral=True)
#Cog Class
class Test(commands.Cog):
def __init__(self, bot):
self.bot = bot
bot.add_view(rpsView(None)) #None parameter for ctx.author
@commands.command()
async def rps(self,ctx):
view = rpsView(ctx)
em = discord.Embed(title=f"Rps Game", description="Choose one of these options. \n :newspaper: Paper\n:new_moon: Rock\n:scissors: Scissors", color=0xfff8b0)
await ctx.send(embed=em,view=rpsView(ctx.author))
async def setup(bot):
await bot.add_cog(Test(bot))
this is cog file btw!
and change this version to yours (nextcord)
Yeah
Good lesson
Haha
self.bot?
yay
im using replit with my bot to run it online 24/7
but what i got banned from discord?
you are trying to abuse something
how do i make a copy button, so when the user presses the button, it sends 2 messages containing the content under “BTC value amount” and “payment address”
type kill 1 in shell and start again
not sure if we are allowed to help with such stuff
do yk where i can find help for that
no idea
bitcoin?
also discord bans bots from currency stuff from the latest toc stuff
especially games like gambling currency exchange and stuff
im just tryna make a copy button for my bot
wdym copy?
like it sends 2 messages containing the value in “btc value amount” and “payment address” when i press the button
if that's is true i cant help 😛
Dms
thank you
is there any way i could get emoji ids
i want to react with ⬆️ to a message
with arrow_up words
Just
:arrow_up: ```
k but await message.add_reaction(":arrow_up") doesn't work
Where's the last : at the end of it
or even the standard emoji is fine like just ⬆️
discord turns the text into emoji if i write tht here 😂
What are you trying to do exactly
!d discord.ButtonStyle
class discord.ButtonStyle```
Represents the style of the button component.
New in version 2.0.
just put the emoji instead of all that
did tht
it's the whole problem
when i go to reactions and click ⬆️ it is recognized as another emoji
rather than the one added from the bot
you need to use the unicode form
And variation selector 16
Ugh it's smth like that lemme see
trying to make a button
the same upvote but recognized as 2 emojis
\U00002b06: UPWARDS BLACK ARROW - ⬆ — http://www.fileformat.info/info/unicode/char/2b06
\U0000fe0f: VARIATION SELECTOR-16 - ️ — http://www.fileformat.info/info/unicode/char/fe0f
use these unicode codes
@sweet pilot
What libs do you have installed?
when adding the reaction?
Yes
why does my copy button not work
Give better explanation
!d discord.Webhook.send - it returns WebhookMessage object. Just get the ID with .id from it
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using the webhook.
The content must be a type that can convert to a string through `str(content)`.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects to send.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
Theres that thing in some bits that they want access to our account how do i add it on my bot?
pls help py webhook = Webhook.from_url(webhook_url) TypeError: from_url() missing 1 required keyword-only argument: 'session'
Give it a aiohttp.ClientSession object
!d aiohttp.ClientSession
class aiohttp.ClientSession(base_url=None, *, connector=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, json_serialize=json.dumps, ...)```
The class for creating client sessions and making requests.
like that ? ```py async def main():
async with ClientSession() as session:
webhook = Webhook.from_url(webhook_url, session=session)
ress = await webhook.send(content="123")
pprint(ress)
if name == "main":
asyncio.run(main())```
Yes
output py None Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000218CDE4B3A0> Traceback (most recent call last): File "E:\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__ self.close() File "E:\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close self._loop.call_soon(self._call_connection_lost, None) File "E:\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon self._check_closed() File "E:\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed
Is this Windows?
yes
Try setting the event loop policy with
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
On top of your asyncio.run
oh, it work, but... why?
it work, but can return id, it return None
Set the wait argument to True
thanks!
help
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
guys is there a reason why this happens on mobile but its fine on pc
the command mention
Try updating your Discord
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 800, in _load_from_module_spec
setup(self, **extras)
File "c:\Users\PC\Desktop\Aleccy Bot\cogs\rps.py", line 31, in setup
bot.add_cog(Test(bot))
File "c:\Users\PC\Desktop\Aleccy Bot\cogs\rps.py", line 21, in __init__
bot.add_view(rpsView(None)) #None parameter for ctx.author
File "c:\Users\PC\Desktop\Aleccy Bot\cogs\rps.py", line 8, in __init__
super().__init__(timeout=None)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ui\view.py", line 190, in __init__
loop = asyncio.get_running_loop()
RuntimeError: no running event loop
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 48, in <module>
bot.load_extension(f"cogs.{fn[:-3]}")
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 888, in load_extension
self._load_from_module_spec(spec, name, extras=extras)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 805, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
nextcord.ext.commands.errors.ExtensionFailed: Extension 'cogs.rps' raised an error: RuntimeError: no running event loop```
Main file
okay
await bot.load_extensions
You need asyn function to load the extensions
yes!
Good
tysmm!
also do u know how to
Remember,the buttons are not working after the bot restart.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
tyyy
can anyone help with my discord bot's database in #databases 🥹
how can i get the msg from id
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
use developer mode, right click the msg and click copy id
thx
had to use Bot.get_channel to get the channel
very informative
👍 i take that as a compliment
it was a compliment 🛐
thanks :D
await cursor.execute("DELETE FROM afk WHERE user = ? AND guild = ?", (author.id, guild.id,))
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 129, in _execute
return await future
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 102, in run
result = function()
sqlite3.OperationalError: database is locked
sending everythinmg twice or 3 times
You have the bot running 3 times most likely
Check task manager.
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 34, in on_ready
await cursor.execute("CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER)")
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 129, in _execute
return await future
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 102, in run
result = function()
sqlite3.OperationalError: database is locked```
Did you check task manager?
Someone help
how did u manage to lockdown aiosqlite 💀
It’s enabled
both in code and applications portal?
How in code sorry I’m begginer
Running your bot twice, it's a concurrency error.
oof
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
nooo??
@bot.event
async def on_ready():
print(f"{bot.user.name} is online!")
setattr(bot, "db", await aiosqlite.connect("levels.db"))
async with bot.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER)")
await cursor.execute("CREATE TABLE IF NOT EXISTS levelSettings (levelsys BOOL, role INTEGER, levelreq INTEGER, guild INTEGERP)")
await cursor.execute("CREATE TABLE IF NOT EXISTS afk (user INTEGER, guild INTEGER, reason TEXT)")
await cursor.execute("CREATE TABLE IF NOT EXISTS warns (user INTEGER, reason TEXT, time INTEGER, guild INTEGER)")
async def addwarn(ctx, reason, user):
async with bot.db.cursor() as cursor:
await cursor.execute("INSERT INTO warns (user, reason, time, guild) VALUES (?, ?, ?, ?)", (user.id, reason, int(datetime.now().timestamp()), ctx.guild.id,))
await bot.db.commit()
OH GOT IT
INTEGERP
nvm that wasnt the problem
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 165, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 148, in afk
await cursor.execute("INSERT INTO afk (user, guild, reason) VALUES (?, ?, ?)", (ctx.author.id, ctx.guild.id, reason,))
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 129, in _execute
return await future
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 102, in run
result = function()
sqlite3.OperationalError: database is locked
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 608, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1382, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 948, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 174, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: database is locked
CTRL+SHIFT+ESC
Bottom right/
Check vscode or python if it is running twice or more.
Okay
holy shit
@cloud dawn i reset my token and now it works perfectly, did someone got my token?
No you just destroyed the other windows because you did that.
You were just running bot twice or more on your machine.
python or python3 ie py or py3 should work i generally make aliases
server is down
RuntimeWarning: coroutine 'music' was never awaited
self.after(error)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
voice.play(discord.FFmpegPCMAudio(source = URL, ** FFMPEG_OPTIONS), after=lambda e: music(ctx))```
what's the matter?
You need to await the coroutine
After doesn't accept coros anyway
crazy
async def unbanid(a: discord.Interaction, user: int)
why does int make user ids not work
what screenshot too lis that
bad indentation
@miner.tree.command(name='unbanid', description='unbans an id from a server, bot must be in it')
@app_commands.describe(user = 'Put a userid!')
async def unbanid(a: discord.Interaction, user: str):
username = a.guild.get_member(user)
try:
await a.guild.unban(user)
await a.response.send_message(f"Unbanned {username}")
except:
if username == None:
await a.response.send_message("No User Found")
else:
await a.response.send_message(f"Couldnt unban {username}")
why doesnt this work?
how can I unban someone?
?
??
ShareX
how u get the colour thing?
I dont rlly remember but u can check a tut
Just use a userconverter.
So pycord apparently has a View within which we can nest action rows, buttons, etc... is that a new component type from Discord or is it a pycord abstraction?
It's from discord.py
When pycord forked discord.py the View class came with it
And it's an abstraction, discord doesn't have any sense of a "view" how we know it
ah
yeah I'm used to writing it out as nested action rows (?) from another language
so I was confused if it was an undocumented discord component type perhaps
discord.py (and forks except disnake) don't use actionrows and have a View interface instead
Hello, I would like to authorize a command in a specific room by server using a sqlite database by doing for example n!commandallow #salon, could you help me ?
Nodejs? I believe they do it like that
Well they do use action rows as well
A view is composed of a maximum of 5 action rows
internally ofcourse, there's no other way around to interact with the api lol
but you can't manually create a ActionRow as in the discord object
serenity-rs got it, nodejs too mb
eh I mostly delve in worker runtimes like CF workers but I think a ton of discord bot libs do the nested action row thing
as that's how it's passed to Discord API in the end
Yes the discord API has an action row so a library must as well
Hello, I would like to authorize a command in a specific room by server using a sqlite database by doing for example n!commandallow #salon, could you help me ? You can help me ?
Or with a .txt file
IS IT POSSIBLE TO ADD A WHILE LOOP IN THE ON READY EVENT
for what ?
CHECK THE NUMBER OF MEMBERS OF A VOICE CHANNEL
like
@bot.event
async def on_ready():
global Channel
while True :
if len(Channel.members) == 0 :
await Channel.delete()
I need one on one help
!d discord.ext.tasks.loop use a task, don't do anything in on_ready
@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").
okay
what do you have rn? or how do you plan to implement it?
you can help me for #discord-bots message ?
What do you mean, I don't understand ?
might claim a help channel in that case
oooo
where are those
ah i see
thx
what to do in the count if wanted it to be unstoppable
#❓|how-to-get-help the claimable ones will be mentioned below
do you have any code you made for that? @slate swan
Not yet
thanks , so can you help me using this loop
hm so your first task would be creating a table in the sqlite db that establishes a relation between disabled command and channel/server id in columns
is #salon in your question meant to be a channel>
can this code work ?
you don't use while True loop in a task it runs forever itself
ok
this can work ?
is there any slash command docs?
the command has to enabled/disabled all bot commands or a specific one?
yes, depends on what library you're using
A specific order
py-cord
i see, can you explain in more brief about how it should work
I want to be able to perform this command in a room that we define with a command n!commandallow.
guide: https://guide.pycord.dev/interactions/application-commands/slash-commands
docs: https://docs.pycord.dev/en/stable/api.html#slashcommand
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
by room you mean a textchannel right?
Yes one text channel for this command per server
yeah then you can just insert the server id and the channel id in the database table when command is used
next, make a check for that command which makes sure that the command was used in the desired channel
import os
import sqlite3
class Command_allow():
def __init__(self, database_name : str):
self.con = sqlite3.connect(f"{os.path.dirname(os.path.abspath(__file__))}/{database_name}")
self.con.row_factory = sqlite3.Row
def command_allow_add(self, guild_id : int, channel : int):
cursor = self.con.cursor()
query = "INSERT INTO command_allow (guild_id, channel) VALUES (?, ?);"
cursor.execute(query, (guild_id, channel))
cursor.close()
self.con.commit()
```I did this to save the information in the db
I don't know how to get the information to compare them
I don't think you're supposed to have 1 always-open connection
SELECT channel FROM command_allow WHERE guild_id = ? would be query in your case
you'll execute it using cursor's fetchone(), the data return type will be tuple with channel id
sidenote: use the async driver of sqlite3
doesnt hurt to have a single connection throughout the bot in a sqlite3 db
!pip aiosqlite
ah
@bot.command()
async def commandallow(ctx, channel : int):
if (not ctx.author.guild_permissions.ban_members):
await ctx.send(f"Vous n'avez pas l'autorisation {ctx.author.mention}")
return
command_allow.add_guild_id(ctx.guild.id, channel)
await ctx.send("Channel defined")``` is good ?
for defined id
def command_allow_check(self, guild_id : int, channel : int):
cursor = self.con.cursor()
query = "SELECT channel FROM command_allow WHERE guild_id = ?;"
cursor.execute(query, (guild_id, channel))
result = list(map(dict, cursor.fetchall()))
cursor.close()
return result```
Is good @slate swan ?
you can actually do ```py
query = "SELECT channel FROM command_allow WHERE guild_id=? AND channel=?"
result = cursor.execute(query, (guild_id, channel)).fetchone()
return True if result else False
this will make the function return True if the channel is allowed , else false
Currently it does not register anything in the database
Does anyone know about xpaths?
return bool(result) 
depends 
does it not insert in database at all?
its python and its based on selenium and chromedriver
change the data types to BIGINT maybe
It does not insert anything
gonna do the same internally anyways
BLOB ?
blob will save it as bytes or string
use BIGINT for longer integers
I d'ont have BIGINT
I test
Still not
try committing before closing the cursor
the database might not have traced the changes because you closed the cursor with changes
How I make him save ?
swap the last 2 lines of command_allow_add function
No...
@commands.has_permissions(ban_members=True)```
You can help me ?
Where is the issue?
Nothing registers in the db
this is windows 10, however on windows 11 it works perfectly fine
This channel is for discord.py libraries
Have you tried mydb.commit() before closing cursor
is there a way that the bot says automaticly thanks when someone boosts the server?
there is no event for boosting
thats kinda sad. But saw that already somewhere else
there is way like answer number two or checking members after 10s and see if they're boosted the server
thats alot ticks after a while :c
this?
yup
there isn't any event dispatched for server boosts, though there are a few workarounds:
on_messagewill be fired if the server has message boosts enabled- the member will get a nitro boost role (which you can check for in
on_member_update)
no, bots don't have that feature. Why not just use a database though?
Thank you!
Will be the "on message" bc some ppl Boost twice yk 😄
so ill just do an privat channel and an open one where the bot sends the "thanks"
i just like to know if that is possible cuz i never saw bot notes a user
yeah got that already still dont figure out ht xd
@bot.event
async def on_message(message):
if message.type == discord.MessageType.premium_guild_subscription:
print(str(message.author))```

do I just put an await under it?
Does this work?
does anyone want to work on a discord bot with me
I dont wanna test XD
xD
Wait... if someone boosts and I say "blabla thanks for the boost".... what do I need to do for Tagging? Author ? xD
no
u can test it on mine 
message.author might work
Try just doing print(message) and then boost
It should print everything about the boost and you can go from there
does anyone want to work on a discord bot with me
so u mean change the last line to "print(message)"
@bot.event
async def on_message(message: discord.Messge) -> None:
message.type = discord.MessageType.premium_guild_subscription # patch
if message.type == discord.MessageType.premium_guild_subscription:
print(str(message.author))
```we do a little trolling
As long as it's not inside the if statement
@sick birch
so yes
@bot.event
async def on_message(message):
if message.type == discord.MessageType.premium_guild_subscription:
await message.channel.send("Thanks for the Server Boost ")
print(message)```
thats what I got for now
Like i said make sure it's not in the if statement
does anyone want to work on a discord bot with me
You've already asked twice. Please stop asking.
ok :(
it works! Lets go thank you Robin 
okay last question... how do I tag them ? I mean "message.author" works lmao 
message.author.mention
feel free to just ask for help when you need here
Got smth already haha , thanks anyway and no, just an gif
theres 3
ohh i see
like that yk ?
@bot.event
async def on_message(message):
if message.type == discord.MessageType.premium_guild_subscription:
channel=bot.get_channel(1043836095374303242)
embed=discord.Embed(title=":wave: Danke für den Serverboost!", description=f"Danke für den Serverboost! {message.author.mention}!)
embed.add_field(name="**Nicht vergessen!**", value="Vergiss nicht deine Vorteile abzuholen!")
embed.set_image(url="https://cdn.discordapp.com/attachments/1035876269394493490/1044436064753950800/ligne-gif-discord-line.gif")
await channel.send(embed=embed)
print(message)```
you dont close the string "
here, is this working? I mean it was working before, but in the channel where the server sends the boost message, I want it in another channel
@bot.event
async def on_message(message):
if message.type == discord.MessageType.premium_guild_subscription:
channel=bot.get_channel(1043836095374303242)
embed=discord.Embed(title=":wave: Danke für den Serverboost!", description=f"Danke für den Serverboost! {message.author.mention}!")
embed.add_field(name="**Nicht vergessen!**", value="Vergiss nicht deine Vorteile abzuholen!")
embed.set_image(url="https://cdn.discordapp.com/attachments/1035876269394493490/1044436064753950800/ligne-gif-discord-line.gif")
await channel.send(embed=embed)
print(message)
but this should work right? and should get send in the channel I put in right? 
worked like that, but wrong channel haha
theres no event for server boosts 🙂
what are you trying to do?
get the announcement channel of boosts?
no lmao
what do I need to do if I want the "Status" to say how many discord members are in my guild?
example: "playing with ... 300 members"
guild.members
it was bot.users for me, but ty
WARNING discord.gateway Shard ID None heartbeat blocked for more than 10 seconds.
What’s this
Do you have any blocking code?
idk what blocking code is
Code that doesn't have await and is I/O (e.g interacts with database, sends request)
yes
should I make them all async?
@sick birch
That won't really work
Can you send your code that isn't async?
def store_api(user_id, api_token):
user_data = {user_id: api_token}
try:
with open(json_file, 'r') as file:
temp = json.load(file)
with open(json_file, 'w') as f:
temp.update(user_data)
json.dump(temp, f)
except json.decoder.JSONDecodeError:
with open(json_file, 'w') as f:
json.dump({}, f)
store_api(user_id, api_token)
def get_api(user_id):
with open('userdata.json', 'r') as file:
content = json.load(file)
if user_id in content:
api_key = content[str(user_id)]
return api_key
else:
return "Error"
def create_catchall(catchall):
firstname = names.get_first_name()
lastname = names.get_last_name()
two = ''.join(random.choice(string.digits) for _ in range(2))
email = f"{firstname}{lastname}{two}@{catchall}"
return email
Stuff like this we can ignore
It's CPU bound
AH I see im sending a request
but idk if the api im sending the request to is within the servers terms so I will pass
yeah fair enough lol
If you're not sure it's within this server's rules it's probably not
every command of my bot doesnt work
Do you have an on_message event?
lets say its a request to get the time in another city...
yes
Do you have process_commands?
no
!d discord.ext.commands.Bot.process_commands
await process_commands(message, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
Changed in version 2.0: `message` parameter is now positional-only.
Add it
oh tyy
@bot.event
async def on_message(message):
Channel = bot.get_channel(1036256958094770218)
if message.author.bot:
return
embed = nextcord.Embed(title=f"New suggestion!", description=f"__**User:**__ \n {message.author.mention} \n \n __**Suggestion:**__ \n{message.content}", timestamp=datetime.now() , color=0x4e80cf)
embed.set_thumbnail(url=message.author.display_avatar.url)
embed.set_footer(text=f" {message.author} | {message.author.guild.name}")
if message.channel is not Channel:
return
moji=await Channel.send(embed=embed)
await moji.add_reaction('✅')
await moji.add_reaction('❌')
await bot.process_commands(message)```
still doesnt work
Do you have message content intents?
yes
Both in the developer dashboard and in the code?
yes
I would double check and be 100% sure because that's the only other issue it could be
intents=nextcord.Intents.all()
Are you using your commands in the channel with ID 1036256958094770218?
nono
Well you need to
I’m not sure how hard this is to answer without looking at the code. Not able to provide it atm.
Are hybrid commands able to work with sql database queries? Was getting a “data cannot be str, must be int” error. Tried some print tests to see where the problem is. Even commented it out to see if removing parts of it would work, just to get any response at all.
Tired using int() to convert it but that didn’t work either.
can you show code?
How to I set a REQUIRED arg so when a user does not add the arg I can send a message to do so?
Dont set a default value.
Without the trackback this will be hard to answer you can make a db work ofc
so I have
async def cmd(self, ctx, arg):
my code...
when I run the command with out an arg, it just doesnt do anything or return an error.
Don’t have the computer the code is on with me currently
I’ll probably be here tomorrow troubleshooting
I think it's better to wait then, this is also most likely a positional issue.
Yea was just wondering if how it was coded previously will still be able to function for hybrid commands without much rewriting
The only thing that changes for an application command is that you need to handle it in 3 seconds else defer it. Otherwise it's pretty much the same inside the function.
How do i start making bots?
Is there a way to host your bot for free?
turn your pc on. foreveeeer

What'd you like to know?
Github, Azure, Google.
free (only if you pay)
how do i like, start
Nothing in life is free, it's worth the money for self development.
Start with making a bot I assume.
What do you want to make.
translator bot
What research have you done so far?
not really anything but i know how it might work
its gonna use sticky translation
so like for example ;ss (sticky start) [language]
;sc (sticky cancel)
Never heard of it.
basically you start the command and it will translate everysingle one of the user that started the command to whatever language
dude im already getting help i know python stop assuming lol
im not a complete newb
you dont need to
Cool
then look at things on the docs
I mean I've already given you a link
Could you guys not? It's a public channel.
exactly
this
Using message command or application commands?
so for example
me: ;ss swedish
bot: swedish selected (idk didnt really think about this part)
me: hey
bot: (my username):hej
does it matter?
Well application commands are a lot cleaner but harder to code.
Oh I get it.
That's pretty doable.
You'd add users who have started it to a db along with what language they want
use the on_message event to get the messages they send
Exactly what? I simply told you what you should know, and a guide to get you started. You decided to start getting aggressive
still getting thisd error
i didnt ask for your help and im not getting agressive im just annoyed that youre getting pushy i cant even start rn because im in class im simply trying to figure out the scope of this project
lol what has the other guy helped you with
Telling u it's doable
Pushy?
just stop ong
RuntimeWarning: coroutine 'music' was never awaited
self.after(error)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
voice.play(discord.FFmpegPCMAudio(source = URL, ** FFMPEG_OPTIONS), after=lambda e: music(ctx))```
what's the matter?
music is async def (coroutine) function
So u need to await it or schedule it with asyncio.create_task
U can also use asyncio.run_coroutine_threadsafe since ig Discordpy uses threads for music playback
It's completely different
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
could u tell me more detail?
Run asyncio.create_task(music(ctx)) in the lambda
and u can also read asyncio docs to learn how it wrks
ok thx!!
They way you load cogs it's... it's..... ... ..
LOL IT WORKED
lemme show u but i have a slight issue tho
Is this cog test2?
KEKW
Besides the list comp... loading it before starting up the bot is actually pretty good.
dont bother about that first
But then again you have to setuphook for that as well.
asyncio.get_event_loop().run_until_complete(main()) I don't see a main so yeah that could be lol
thats the old version
Yep I could show you my client.
.
I've looked
i deleted this in main.py and it worked btw
👀
Does it work?
Looks fine to me
really? lmao
this means it connected to the db right?
Yep
?
what is that
How you get the value
Yes
this
await ctx.send(var[0]["matchplayer"])
asyncpg is the best
ye
amazing wtf error is this
'matchplayer'
best error of the year
'error'
Your logger is just having a stroke.
But my guess is that we need something else to get the value.
how do i even make railway.app log error normally
💀
i literally need to log like this
how are you starting the bot?
do you use bot.run?
wdym
Do you use it or not
bot.run(token)
ok
import asyncpg
import asyncio
loop = asyncio.get_event_loop()
conn = loop.run_until_complete(asyncpg.connect())
r = loop.run_until_complete(conn.fetchrow('''
SELECT oid, rolname, rolsuper FROM pg_roles WHERE rolname = user'''))
r
<Record oid=16388 rolname='elvis' rolsuper=True>
r['oid']
16388
r[0]
16388
dict(r)
{'oid': 16388, 'rolname': 'elvis', 'rolsuper': True}
tuple(r)
(16388, 'elvis', True)
Using dpy 2.0 and not getting any errors? This is on purpose, the library now uses logging to send errors but only if you're using Client/Bot.run.
It's recommended to setup logging yourself if you aren't using .run or use the utils.setup_logging helper function: just put discord.utils.setup_logging() anywhere in your running file. Docs: https://discordpy.readthedocs.io/en/stable/api.html#discord.utils.setup_logging
I was right.
💀 what had i done
this is all i have done
whyd you change to bot.run without changing other code? this is for when you arent using an async start
just use utils.setup_logging
im confused
You need to use .start and not .run yeah.
what about the log thing
No clue I've got my own logging.
No
just add utils.setup_logging()
at where
main.py or all of these
main
yes
ok
now its even better
no error at all
not even 'matchplayer'
do i need parameter like the docs tho
what parameter? leaving it like that is fine
but its not logging anything
its only outputting 1
yes it is
.
but
what are you expecting?
some error
its supposed to output
1
value from database
2
but it only outputted 1
alr the error is coming
what is this 🥹 @cloud dawn
most prob indention error, because there is no uunicode character as i see
can u send a full ss?
what do i need to add for it to be able to read / print the unicode
ahh then just to ignore this error use try and except statement
? why would i ignore the error lol
i mean if u want to use this unicodes also if u dont want these errors then just use this simple thing
-> best
I think you need to specify the encoding at the top of the file
do u want it to be ugly or not run at all 💀
or you could just fix the problem
ty, let me look at it
try printing var, to see what things are in var
queries from a sql db is generally a iterable so u would need to index it
make help command when?
@shrewd apex
is he or she even using sql db? 💀
asyncpg postgres read the code
oh, my bad
also bruh u are returning before closing the connection why would u want to close the connection in first place just make the conn as an attr of bot instance and use it throughout
It's just better to make a class with helper functions and use those functions 😔 looks cleaner and easier to debug/modify
mhm and dataclasses
yep, that too
attrs better 
hmm well yeah if attrs is ahead of dataclasses
kinda equalising in 3.10
!d attr there's one inbuilt too
oo nvm this another one
I need help. Idk why channel is None.
intents.guilds = True
channel = bot.get_channel(CHANNEL_ID)```
`AttributeError: 'NoneType' object has no attribute 'send'`
u r getting from the cache before the bot is getting ready
I tried several channel ids
because you're using that before the bot is running
I love seeing messages of people getting pissy when help is offered. “i KnOw hOw” but then “help with everything please?
”
what is the shortcut for rerun in terminal
You can just push the up arrow key to get your most recent command
Do you guys know of decent guides to creating discord bots?
i think that what are you looking for https://discordpy.readthedocs.io/en/latest/quickstart.html
thank you. Yeah I was looking into creating a bot to web scrape some anime news and another for music like jazz that can stay playing music
i don't have a tut for music bot but with web sc you can use Beautifulsoup
Thanks!
What do you use to automate the program contrab? Maybe?
wdym by automate the program?
and contrab?
Idk that is some I have heard but I have yet to use it.
By automate I mean, that as soon as the website gets updated with new anime anime news such as upcoming releases will be automatically announced by the discord-bot.
I am not sure if that process needs to updated. I thought beautifulsoup was good for static pages therefore if the page is updated with new information the bot would have to continuously scrape the page?
I am not too familiar tbh. Thank you for your patience
you can do inf loop and check if there is a new data
Music bots are against ToS
are they always been against the ToS?
Yup
It's against YouTube's ToS
They have been but Discord started enforcing those after the Groovy-YouTube lawsuit
oh okay now that make sense
Oh that’s a good point!
Wait is there another way or source to get music from aside from YouTube?
There's Soundcloud iirc
but put time after every loop like sleeping for 5s than check again so you don't use alot of the memory and so the website
People say it allows streaming music but not sure
SoundCloud and they are chilled as long as you ain't downloading and distributing it
didn't get a single mention yet sadly
just shows how miserable the condition of app commands is 😔
So is there a guide to creating a music bot using sound cloud?


