#discord-bots
1 messages · Page 188 of 1
Like asyncio.Queue
the example says otherwise
https://discordpy.readthedocs.io/en/latest/ext/tasks/
The GitHub example says otherwise
https://github.com/Rapptz/discord.py/blob/master/examples/background_task.py#L13-L25
examples/background_task.py lines 13 to 25
async def setup_hook(self) -> None:
# start the task to run in the background
self.my_background_task.start()
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
@tasks.loop(seconds=60) # task runs every 60 seconds
async def my_background_task(self):
channel = self.get_channel(1234567) # channel ID goes here
self.counter += 1
await channel.send(self.counter)```
you changed...?
They probably forgot to change the docs
ah, loading cogs correctly ftw Ig
no, I think starting a task in async context isn't essential
they just do it in setup_hook because it's a startup / background task
now fix the other stuff and you're all set
the other stuff? you mean the redundant on_message?
.
^ use your setup_hook more
no, do that in your setup_hook
you don't want a redundant if statement, doesn't matter if it gets triggered or not
The example doesn't lie
you copy pasted what exactly?
Even trying to create new loop doesn't help, you need to run it in a async function đ€·
ah, you just started outside the loop, I see
you're right most likely, stinky tasks
the question now is, where would you want to start a task when loading a cog?
Did you start the loop
Good question
In cog_load & cog_unload
right, yup
You should make sure to unload in cog_unload otherwise you might get two running loops
And during active development that screams undefined behaviour too me
you mean stop / cancel?
@pliant gulch hello!
async def button2(self,interaction: discord.Interaction, Button: discord.ui.Button):
await interaction.response.send_message("Sorry, not available working soon.", ephemeral=True) ``` problem error no solution URL button?
Link buttons cannot be made using the decorator. Instead, make then in the __init__ of your view
https://github.com/Rapptz/discord.py/blob/20c7e261be125f4ad28a72550e0727c5b0380d11/examples/views/link.py#L30-L33
examples/views/link.py lines 30 to 33
# Link buttons cannot be made with the decorator
# Therefore we have to manually create one.
# We add the quoted url to the button, and add the button to the view.
self.add_item(discord.ui.Button(label='Click Here', url=url))```
uhh hmm ok check
@wicked atlas example look correct?
put the second line you're pointing to inside your __init__ as well
Already look image
you've put a url variable there, but not the self.add_item(...) line
your __init__ ends here
hmm maybe confuse lol: try code:
def __init__(self):
super().__init__(timeout=None)
self.participants_count = 0
url = 'https://www.google.com/search'
@discord.ui.button(label="Participate", emoji="đ", style=discord.ButtonStyle.primary)
async def button(self, interaction: discord.Interaction, Button: discord.ui.Button):
if interaction.user.id in participants:
await interaction.response.send_message("You are already in the giveaway!", ephemeral=True)
else:
if participantRole2 != None:
if participantRole not in interaction.user.roles and participantRole2 not in interaction.user.roles:
await interaction.response.send_message("You dont have a role!", ephemeral=True)
else:
await self.adduser(interaction)
elif participantRole not in interaction.user.roles:
await interaction.response.send_message("You dont have a role!", ephemeral=True)
else:
await self.adduser(interaction)
self.add_item(discord.ui.Button(label='View Giveaway', url=url))
#@discord.ui.button(label="View Giveaway", emoji="đ", style=discord.ButtonStyle.secondary)
#async def button2(self,interaction: discord.Interaction, Button: discord.ui.Button):
# await interaction.response.send_message("Sorry, not available working soon.", ephemeral=True) ```
try you code fix?
button there last #@discord.ui.button(label="View Giveaway", emoji="đ", style=discord.ButtonStyle.secondary) ....?
is ignore no?
Yep, link buttons can't be created using the decorator, so you can remove that
đ
buttons_pressed = []
view = View()
counter = 1
correct_answers = []
async def call_1(interac):
num = 1
buttons_pressed.append(num)
await interac.send(f"Selected answer: {num}")
if len(buttons_pressed) == len(correct_answers):
if buttons_pressed != correct_answers:
await interac.send(f"You haven't selected the correct answers! You can try again after 30 minutes.")
return
print(buttons_pressed)
async def call_2(interac):
num = 2
buttons_pressed.append(num)
await interac.send(f"Selected answer: {num}")
if len(buttons_pressed) == len(correct_answers):
if buttons_pressed != correct_answers:
await interac.send(f"You haven't selected the correct answers! You can try again after 30 minutes.")
return
print(buttons_pressed)
async def call_3(interac):
num = 3
buttons_pressed.append(3)
await interac.send(f"Selected answer: {num}")
if len(buttons_pressed) == len(correct_answers):
if buttons_pressed != correct_answers:
await interac.send(f"You haven't selected the correct answers! You can try again after 30 minutes.")
return
How do I make it so I can make 10 buttons to a message using a for loop but also add a callback to each button without creating 10 callback functions?
Perhaps within the for loop? Because when I do it just makes the function of the last iteration in the loop (e.g. 10th function)
this is where subclassing discord.ui.Button would significantly improve your code because then you could achieve a syntax like this: ```py
view = discord.ui.View()
for i in range(1, 10):
view.add_item(AnswerButton(i))
send view
``` though of course each button needs some way to know the answer, and thats where you'd ideally want to encapsulate your view's state in a discord.ui.View subclass
the tic tac toe example on github is an alright example if you want to figure out how they organized the logic between the buttons and the view
https://github.com/Rapptz/discord.py/blob/master/examples/views/tic_tac_toe.py
i would just use the custom id ig
why now it tolds me this, i already add ffmpeg to enviroment variables and the path is correct
discord/discord-api-docs#3961
presumably other flags they might have arent documented for a similar reason
looking at the docs you're not meant to just pass the folder but the full path to that executable, in your case probably C:\ffmpeg\bin\ffmpeg.exe
or you could add C:\ffmpeg\bin to your PATH environment variable and not have to configure executable= at all, which might be more ideal if you have (or will have) some other software that needs ffmpeg
nah, i dont have other software that uses ffmpeg, but let me try
still giving me the same error

which approach did you take? if its changing PATH, you'll need to restart your terminal/editor for your changes to apply
oooh okay, let me restart
still the same error

okay, let me share the tutorial i follow to install ffmpeg
how can i make errors log into a channel instead of console
looks fine, did you remove your executable= argument too?
you can handle the on_command_error event and send an embed there, though i would still suggest printing the traceback for unknown errors since that's quite important for debugging
yeh but says this
how
by errors i dont mean any specific error but instead anything that is logged into the console
i mean removing the entire argument, not just the keyword part of it
even the path?
what else are you trying to handle? the on_command_error is invoked for all errors related to commands
changing executable="..." to "..." is not removing the argument, you're merely changing it from a keyword argument to a positional argument, hence why the syntax error appeared
speaking of which that argument is almost certainly interfering with it since \f and \b are being recognized as escape sequences
soo, how i should write it?
either dont write it at all, or fix it so your file path isnt messed up by the escape sequence detection ```py
Let discord.py find ffmpeg in PATH
discord.FFmpegPCMAudio("my_audio.mp3")
...or escape each backslash so they're treated literally
discord.FFmpegPCMAudio("my_audio.mp3", executable="C:\ffmpeg\bin\ffmpeg.exe")
...or prefix the string with "r" to make it ignore escape sequences
discord.FFmpegPCMAudio("my_audio.mp3", executable=r"C:\ffmpeg\bin\ffmpeg.exe")
...or use forward slashes which are supported on windows
discord.FFmpegPCMAudio("my_audio.mp3", executable="C:/ffmpeg/bin/ffmpeg.exe")```
alright, let me try bro
Oh
bro im starting to think that is vscode
cuz NO ONE of the options work
let me reinstall vscode
why i do config.config it shows me error line
What error line
U need _init_.py in the package
ohh
you see the config.config
U can click on Problems tab and it will tell you
Yea because you need to add init.py in config dir to mark is as package
Working on a message delete log and I tried to make it so it detects deleted images too. It work when there's:
text no image, text 1 image and image no text but whenever I have text and 2 images or no text 2 images it always either replaces the text with a duplicate image or duplicates an image regardless. Any thoughts?
@bot.event
async def on_message_delete(message):
if message.author.bot:
return
embed = discord.Embed(description = f"**A message sent by {message.author.mention} has been deleted in <#{message.channel.id}>**\n{message.content}", color = 0xf6ff00, timestamp = discord.utils.utcnow())
if message.attachments:
if len(message.attachments) == 1:
if message.attachments[0].url.endswith(('.jpg', '.png', '.jpeg', '.gif')):
embed.set_image(url = message.attachments[0].url.replace('cdn.discordapp.com', 'media.discordapp.net'))
else:
embed.add_field(name="Attachment", value = message.attachments[0].url)
else:
for attachment in message.attachments:
embed = discord.Embed(description = f"**A message sent by {message.author.mention} has been deleted in <#{message.channel.id}>**", color = 0xf6ff00, timestamp = discord.utils.utcnow())
embed.set_image(url = attachment)
channel = bot.get_channel(1067413418597953637)
await channel.send(embed=embed)
embed.set_author(name = f"{message.author.name}#{message.author.discriminator}", icon_url = message.author.avatar)
embed.set_footer(text = f"User ID: {message.author.id} âą Message ID: {message.id}")
channel = bot.get_channel(1067413418597953637)
await channel.send(embed = embed)```
Also noticed the duplicate log has the user and message ID whilst the others do not
Hi!, i got a question, how i should give to discord.FFmpegPCMAudio() the source?
i tried like this, but it tolds me this problem (the urlself.mp3 is in the same folder than my cog file)
How to add voting system in a discord bot like after every 12 hrs it sends a reminder
Because the channel.send is not inside the if statement
can anyone help me
Have you made the voting system and you want to add the reminder?
Or are you doing everything from scratch
I wrote a paginator for discord embeds. I don't understand what's wrong with it and why the footer does not change the page number when switching, and why the "Previous" button is always disabled.
https://mystb.in/RangersValuesChristian
requests is blocking btw
help meeee
I started only 1 file with bot*
?
it's down?
that means we can't use it for now?
not what they meant
https://discordpy.readthedocs.io/en/latest/faq.html#what-does-blocking-mean
You can set original interaction as attributes of your subclass and use delete_original_response() on timeout
example pls?
class YourView(disnake.ui.View):
def __init__(self, inter: disnake.ApplicationCommandInteraction):
super().__init__(timeout=180)
self.inter = inter
async def on_timeout(self):
await self.inter.delete_original_response()```
but how would i get that inter at the first place
Ah yes I look like a spoonfeeder
In a command
im using listenr
If it is just a view attached to a message then use message instead of interaction
Same principle
ohk now i get it
sorry đ , and thanks
non discrod bot related but how can I fix this? im trying to make a discord bot
hi, why it dont work please?
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
intents = discord.Intents.all()
bot = commands.Bot (command_prefix="!", intents=intents)
class automsg(commands.Cog):
def __init__(self, bot):
self.bot=bot
@commands.Cog.listener()
async def on_message(self, message):
liste = ("Bonjour", "bonjour", "Bonsoir", "bonsoir")
liste2 = ("Bonne soirée", "bonne soirée", "Bonne nuit", "bonne nuit")
nombre_mention=len(message.mentions)
for x in message.mentions:
if (x==bot.user):
await message.channel.send (f"DĂ©solĂ©, je ne me parle pas Ă moi mĂȘme...")
Aren't snipers disallowed?
I don't know I can't read half the text. Try saving the file you're editing with cntrl + s or ensure that the file actually exists.
You do
What are snipers?
Logging deleted messages
I figured tons of bots have them so i assumed it was okay, is that incorrect?
tons of bots also have/had music until discord said yeet ÂŻ_(ă)_/ÂŻ
You need to read ToS by yourself or ask discord support
Actually they don't give a frick until somebody reports but that's not gonna happen cause nobody reads ToS
and discord doesn't read reports
Discord's privacy policy broke some laws in like France, didn't it? XD?
I heard about that
what is the error you are getting?
XDDD
I still have music on my bot because some other people do and IDK if its actually not allowed or not
If you're downloading it from youtube it is not allowed
Time to switch to spotify đ
or maybe not, I don't think it matters if it's not monetized
Spotify doesn't have API afaik
it doesn't rlly matter u can still download songs from it XD
or stream them to a vc
I have no error but the bot still responds to itself
also AFIAK they do
Discord is getting rid of music bots with those activities
IDK why I don't think it's a violation of copyright unless it's monetized
Well is there endpoint for streaming music
I don't know I haven't looked very far into it
Spotify URIs and IDs
In requests to the Web API and responses from it, you will frequently encounter the following parameters:
PARAMETER DESCRIPTION EXAMPLE
Spotify URI The resource identifier that you can enter, for example, in the Spotify Desktop clientâs search box to locate an artist, album, or track. To find a Spotify URI simply right-click (on Windows) or Ctrl-Click (on a Mac) on the artistâs or albumâs or trackâs name. spotify:track:6rqhFgbbKwnb9MLmUQDhG6
Spotify ID The base-62 identifier that you can find at the end of the Spotify URI (see above) for an artist, track, album, playlist, etc. Unlike a Spotify URI, a Spotify ID does not clearly identify the type of resource; that information is provided elsewhere in the call. 6rqhFgbbKwnb9MLmUQDhG6
Spotify category ID The unique string identifying the Spotify category. party
Spotify user ID The unique string identifying the Spotify user that you can find at the end of the Spotify URI for the user. The ID of the current user can be obtained via the Web API endpoint. wizzler
Spotify URL An HTML link that opens a track, album, app, playlist or other Spotify resource in a Spotify client (which client is determined by the userâs device and account settings at play.spotify.com. http://open.spotify.com/track/6rqhFgbbKwnb9MLmUQDhG6
Well seems like only metadata
I mean
You can still download songs from spotify the other way :p
XD
you can try
if not message.author.bot
to exclude bots
Or like probably
not message.author == self.user:
If it's in a cog
with else reply with "blablabla"?
?
I wish that if the bot is mentioned then it must send this message "blabla"
Oh that's what ur asking?
yes
dont work, i tried it...
tried what?
user.mentionned_in(message)
bot.user in message.mentions
it's not user.
this is bad, it will be True even if the mention was an everyone or a role ping
it would be whatever_ur_user_is.mentioned_in
or even if someone replied to the bot
if bot.mentionned_in(message)
await message.channel.send (f"DĂ©solĂ©, je ne me parle pas Ă moi mĂȘme...")
it dont work
!d discord.Client.user
property user```
Represents the connected client. `None` if not logged in.
!d discord.ClientUser.mentioned_in
mentionned
mentioned_in(message)```
Checks if the user is mentioned in the specified message.
also that ^
read.
i dont understand the doc... đ
if(self.client.user.mentioned_in(message)):
await message.channel.send("Bonjour, comment allez-vous?")
you just read it.. what? you can clearly see Client.user, if Bot is a subclass of Client what else could it possibly be
bot.user returns the user of the bot
message.mentions returned tue mentioned users in the message
bot.user in message.mentions is if the bot was mentioned in the message
as simple as it gets
if it's in a cog
reason to not use mentioned_in ^
bc you need class discord.abc.User
Ok well you can also just
if(self.client.user in message.mentions):
await message.channel.send("Bonjour, comment allez-vous?")
it's not a big deal
đż
right!
spookie
cookie
there's like 4 ways to do this
discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.
Example
```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
Cool
thats for the prefix specifically
i try it now!
Idk what he is trying
not for checking if the bot was mentioned in message
So.... 
His instructions are not clear
im trying to survive ha. ha. ha.
there is several ways to answer this question
Oh so he is trying to check if bot in the message's mention or not xd
yeps
ye lol. lol. lol.
atleast from the current context
@cunning pasture i tried it and work fine
class automsg(commands.Cog):
def __init__(self, bot):
self.bot=bot
@commands.Cog.listener()
async def on_message(self, message):
liste = ("Bonjour", "bonjour", "Bonsoir", "bonsoir")
liste2 = ("Bonne soirée", "bonne soirée", "Bonne nuit", "bonne nuit")
nombre_mention=len(message.mentions)
if(self.bot.user in message.mentions):
await message.channel.send (f"DĂ©solĂ©, je ne me parle pas Ă moi mĂȘme...")
return
i use "return" because i use other condition at the bottom of code
thanks all
I don't actually know
The primary reason behind YouTube taking down these music bots is that both bots offer a premium subscription that offers a tad bit of extra features on Discord. As Google confirmed to The Verge, Google took down Groovy as it violated its Terms of Service, including modifying the service to use it for commercial purposes.
ÂŻ_(ă)_/ÂŻ
youtube doesnt support any kind of automations in general, it's against their ToS
- access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeâs robots.txt file; (b) with YouTubeâs prior written permission; or (c) as permitted by applicable law;
- collect or use any information that might identify a person (for example, harvesting usernames or faces), unless permitted by that person or allowed under section 3 above;
- use the Service to distribute unsolicited promotional or commercial content or other unwanted or mass solicitations (spam);
What do discord.py cogs do exactly? I've only ever heard partial bits of info on them
Make your code more organized and cleaner
Yeah i should definitely look into them then since I have 688 lines on one .py file đ
Im looking to make a Discord bot that displays Embeds, that i can put information in (For announcement/rules display purposes)
Does anybody have a good template? Im finding it hard to find.
if you do feel free to send me a friend request or tag me đ thanks
I can help u with that

Feel free to dm me bro
Anyone want to make a discord bot for me?
Depends
How many lemons am I getting?
At least 0.5
1*3
0.7*4
0.725*4?
Uhh
I have an idea
Gimme 0.7*4 lemons and u can code the bot yourself
Okay deal
Tf going on here
Bargaining a good lemon deal
Convincing Hunter to get better at coding.
My ass
Get back to work
No Discord bots lol, I've pretty much made everything.
I'm coding for my internship still
Oh nice
Best of luck!
FastAPI + Alembic with React, TS + Chakra
can i just copy paste stackoverflowed code as a contribution?
Hmm
Does it have a Client with slash commands that has extensions?
My way of doing it is still.. .interesting to say the least.
đ i have 3 clients, talk about one
Why use a Client for slash commands
Time to create a custom private wrapper for the API!
Because Bot sucks ass
we can have bamboo trees instead of command trees in our wrapper
Or create a panda plugin
Will be a pain to code the updates tough.
discord.ext.panda
I don't credit myself in code, but I sure as hell do code with panda's in mind.
now i want to make a dpy extension with alternative app commands style
Once I got 30+ years of experience, finally, I can create the ultimate Discord bot.
You need to host a mongodb server for that.
!pip motor
use the python driver and use it to connect to your url
He would need a host first tough.
right right
can anyone tell me step by step
I'm guessing he got a local host rn.
or a video
are you aware of mongodb atlas?
and u r right
i tried it
didnt work
whats this motor thingy
Okay so you need to buy a host since otherwise you can better run the bot on your own pc. But it defeats the purpose of repl.it. Long story short, you can't use mongoDB without paying.
that's how you use mongodb in a async python environment, basically pymongo for async code
free......
You simply can't.
atlas is basically free
what issue did you face
Just use a VPS and a docker compose.
there was no error on replit
but on pycharm it was working

i was ab to say
just buy a vps for like $5 with 4gb
u can easily run a proper bot on there
u can most def find cheaper ones too
4gb pff then you can run like 16 bots
thats what im saying
@slate swan
Minecraft server on the side.
Thats what I mean
hllo
Been playing some astroneer too.
Anyone have some example of function run on nextcord using Context.invoke?
You need to pass a command object.
@maiden fable yo still remember me :D
Either using Bot or the Context object then you need to get the right command. Using Bot.commands you can geta a list of commands, using nextcord.utils.find you can find it using the syntax as stated here -> ```py
member = nextcord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
hm i need to run function (nextcord bot) from python not from discord or the bot itsolf
Yea I remember u having a different much bigger name
Zalgo is not allowed on the server, hence.
My username goes brrrr
That's not zalgo
how say HI to discord form python:)?
HÌŽÌŸÍu̶̜ÍnÌžÍÍtÌ·ÍÌeÌŽÌÌr̶ÌÌ ÌŽÌÌ|Ì·ÌŸÌ Ì”ÌÍáÌžÍÌŸá̞̜ÌáąÌ¶ÍÌ Zalgo go yeet
Wait I don't remembered it being zalgo or smth
Wasn't it a simple English lettered name?
What?
Mayonnaise on an escalator
A random Person
i mean to run bot the function, not member dialog:)
Yes
I don't get it
How can i edit the embed before i sending it
with attribute assignments and method calls...? that's the only way to modify a discord.Embed object
if you mean like editing an embed on an existing message, you just take the embed and change it, although it might be a safer idea to create a copy of that embed beforehand py embed = message.embeds[0].copy() embed.title = "New title" await message.edit(embed=embed)
Does discord py support slash commands now ?
That is correct
No one told me even in docs
Is there a start base ?
Simple code to see
Here's an example
Thanks
i have this code ```py
import discord
from discord.ext import commands
import aiohttp
from bs4 import BeautifulSoup
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0'
}
client = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@client.command()
async def celebrity(ctx, name):
name = name.replace(' ', '_')
url = f"https://fr.m.wikipedia.org/wiki/{name}"
await ctx.send(f"URL : {url}")
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
await ctx.send(response)
if response.status == 200:
soup = BeautifulSoup(await response.text(), "html.parser")
images = soup.find_all("img")
if images:
for image in images[:3]:
url = "https:" + image["src"]
async with session.get(url) as r:
if r.status == 200:
await ctx.send(file=discord.File(await r.read()))
else:
await ctx.send("Aucune image trouvée.")
else:
await ctx.send("Une erreur est survenue.")
client.run(token)```
im trying to scrape image from the site wikipedia.org
but I receive an answer in the form of text encoded in UTF-8 while I requested images
You're sending the response, which sends that huge text
await ctx.send(response)
Also, surely Wikipedia has an API?
yes because i wanted to know if it does the request to the right site if the site exist
but u can see i have a awaiy ctx.send(file=discord.File(await r.read()))
Have you tried sending the URL instead?
yes and it goes to the right site
No, url = "https:" + image["src"] this url
this line get the logo url đ
im not sure i cant get the images because theres in not the option 'save the img as'
where is ur bot = commands.Bot() ?
File "main.py", line 7, in <module>
bot = commands.Bot(command_prefix='.', Intents=discord.Intents.all())
TypeError: __init__() missing 1 required keyword-only argument: 'intents'```
Well what's there to say?
i have all intents enabled
Intents -> TypeError: __init__() missing 1 required keyword-only argument: 'intents'
Hello, my Bot can't load cogs,
that's the script;
async def load():
for filename in os.listdir(r'./cogs'):
if filename.endswith('.py'):
await bot.load_extension(f'cogs.{filename[:-3]}')
async def main():
await load()
await bot.run(token)
asyncio.run(main())
Hey @raven kite!
It looks like you tried to attach file type(s) that we do not allow (). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
TypeError: object NoneType can't be used in 'await' expression
Hi! Im making a function that records user button presses in an embed, is there a way in my slash command to wait for when there is a return of True or False?
idk i was doing something like this
ok = await asyncio.wait_for(funcs.verification(inter, 0), timeout=None)
print(f"Value of ok: {ok}")
if true and if false
run isn't a coroutine
if message.author not in(guild.members) or self.bot not in(guild.members):
await message.author.send('Your message was not sent to the mods. Please double check and make sure both you and I are in that server.')
return
``` Can someone help me with this error please?
im trying to make an if statement to check if both a user and my bot are in a guild
```py
0|bot | Ignoring exception in on_message
0|bot | Traceback (most recent call last):
0|bot | File "/usr/local/lib/python3.8/dist-packages/nextcord/client.py", line 512, in _run_event
0|bot | await coro(*args, **kwargs)
0|bot | File "/home/Runa/bot/cogs/moderation.py", line 161, in on_message
0|bot | if message.author not in(guild.members) or self.bot not in(guild.members):
0|bot | AttributeError: 'NoneType' object has no attribute 'members'
message.author is None
ah thank you!
Comp is my discord cleint and i defined it here
if guild.get_member(message.author.id) is None:
```could someone please help me with this error? im trying to make an if statement to check if a user is in a guild
```py
0|bot | Ignoring exception in on_message
0|bot | Traceback (most recent call last):
0|bot | File "/usr/local/lib/python3.8/dist-packages/nextcord/client.py", line 512, in _run_event
0|bot | await coro(*args, **kwargs)
0|bot | File "/home/Runa/bot/cogs/moderation.py", line 162, in on_message
0|bot | if guild.get_member(message.author.id) is None:
0|bot | AttributeError: 'NoneType' object has no attribute 'get_member'
You are defining the bot 2 times.
Just use one.
Define the guild
message.author.guild.get_member
guild is defined here guild=self.bot.get_guild(msg.content)
basically, someone is supposed to DM the bot a server id.
so I dm my bot a server id, which is stored in msg.content
You want this work in dms?
so which one do i delete
yes, trying to make a mod mail basically
so its basically goes like:
User sends bot a message
Bot: please give me the server ID you want to send this to
User: server.id
Bot: your message has been sent!
@commands.Cog.listener()
async def on_message(self,message):
if message.guild is None and message.author.bot is False:
await message.author.send('Please provide the Server ID of the server you want to send the message to. For example: 702824491667161160')
try:
msg = await self.bot.wait_for('message', timeout=15.0)
except asyncio.TimeoutError:
await message.author.send('You didn\'t answer in time, please be quicker next time!')
return
#if the member or bot are not in the mentioned server
guild=self.bot.get_guild(int(msg.content))
if message.author.guild.get_member is None:
await message.author.send('Your message was not sent to the mods. Please double check and make sure both you and I are in that server.')
return
0|bot | Ignoring exception in on_message
0|bot | Traceback (most recent call last):
0|bot | File "/usr/local/lib/python3.8/dist-packages/nextcord/client.py", line 512, in _run_event
0|bot | await coro(*args, **kwargs)
0|bot | File "/home/Runa/bot/cogs/moderation.py", line 161, in on_message
0|bot | if message.author.guild.get_member is None:
0|bot | AttributeError: 'User' object has no attribute 'guild'
if guild == discord.Guild
so should i put the if message.author.guild.get_member inside an if guild==discord.Guild?
For first
You need to define if the message is on dms or guild channel
how and where would i do that?
if isinstance(message.channel, discord.DMChannel):
discord.DMChannel is enough
đ
may someone please help
sorry, where would i put this? would it be
try:
msg = await self.bot.wait_for('message', timeout=15.0)
if msg(nextcord.DMChannel):
pass
What we are trying to do now
Waiting for what message? After user sends the guild id?
yes msg is the one where the user sends the guild id
the guild id
Read this wait_for example https://gist.github.com/Soheab/e73ab6f66881ee4102be37815da3a24e
thanks for the example! i changed my code to this
@commands.Cog.listener()
async def on_message(self,message):
if message.guild is None and message.author.bot is False:
await message.author.send('Please provide the Server ID of the server you want to send the message to. For example: 702824491667161160')
def check(m: nextcord.Message):
return m.author == message.author and m.guild is None and m.content.isdigit()
try:
msg = await self.bot.wait_for('message', timeout=15.0, check=check)
except asyncio.TimeoutError:
return await message.author.send('You didn\'t answer in time, please be quicker next time!')
#if the member or Runa are not in the mentioned server
guild=self.bot.get_guild(int(msg.content))
if guild==nextcord.guild() is False:
return await message.author.send('You did not provide a server ID. Please resend your message and try again.')
if message.author.guild.get_member is None:
return await message.author.send('Your message was not sent to the mods. Please double check and make sure both you and I are in that server.')
```now im getting this error. do you know what i should be fixing?
```py
0|bot | Ignoring exception in on_message
0|bot | Traceback (most recent call last):
0|bot | File "/usr/local/lib/python3.8/dist-packages/nextcord/client.py", line 512, in _run_event
0|bot | await coro(*args, **kwargs)
0|bot | File "/home/Runa/bot/cogs/moderation.py", line 162, in on_message
0|bot | if guild==nextcord.guild() is False:
0|bot | TypeError: 'module' object is not callable
if guild == discord.Guild
oh capital G?
discord.Guild is object
Yes and remove brackets ()
but you already do this check
if message.guild is None
So just use else (if guild exists)
Oh nvm now I see what you did
i think the issue is that every time i send the bot a message its just going to trigger the entire on_message event to run again. maybe i should try using buttons/embeds or something for mod mail
I can tell you how I would do it.
sure!
You can use a select menu
And create a option for each guild
But maybe you need to work on it
dm me if you know how to make embeds in self py
Because if the bot and user share many guilds (50+)
You will need another and faster way to define the guild.
You got me?
ahh i see. thank you so much
It's not good method
If user and bot share many guilds.
But you can optimize it
i'll look into it tomorrow, thank you for the suggestion
does anyone have know if its possible to fetch a number of results using a specific search in the search bar?
Like this
Using bot right?
yes discord.py
if you mean through the bot you can't use that type of search as its limited to actual users only
ah ok, thank you
but you can use history to check through channel history
any alternatives do you think?
ah
let me find the docs for it rq
You can use channel history
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destinationâs message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this.
Examples
Usage...
Ok. because I wanted to make a counter of messages sent in a channel and it would take the amount of results and send it when a player runs a command
you can also call this on VoiceChannels & DMChannels
this could be hard to do with ratelimits depending on how many messages are in the channel and what you're trying to count exactly
makes sense
alternatively you could just track message counts yourself with an on_messsage (if all you're trying to do is count messages sent in channels) and then save that count for each channel to a database, but ofc you wont get the total channel count, only what your bot could see in the time its had access to the channel
Hey how do i get a user from their ID using discord API because the bot does not share any servers with that user
this is what i got so far but i got an error
make a request in discord API
/users/{user.id}
The id will be the first in result
can you write an example or send some documentation pls
Integrate your service with Discord â whether it's a bot or a game or whatever your wildest imagination can come up with.
No I can't write code for you .
how to edit a voice channel name?
get channel and then you can do
channel.edit(name=newName)
!d discord.Guild.get_channel
get_channel(channel_id, /)```
Returns a channel with the given ID.
Note
This does *not* search for threads.
Changed in version 2.0: `channel_id` parameter is now positional-only.
how do i make it so the user can put in 2 options and depending on what they type on second option it sends a different thing with slash commands?
how can i get my self to joina server using my own self bot
i have this :
@commands.command()
async def say(self, ctx, *, arg):
await ctx.send(f"{arg}")
await ctx.message.delete()
what is the condition to add to prevent the bot from talking to itself if I mention @bot in the !say command?
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
đ€
Excuse me?
"excuse me" - đ€ đ»
Quoting someone and putting a nerd emoji after it does not give your argument any credibility, FWIW
No more selfbots
what can i do with a self bot 
You're also not getting help with that attitude, disregarding the fact that it's malicious
and whys it so bad
It's in violation of Discord's terms of service
why
Because there's not many legitimate reasons to be automating a user account
there is
what could the malicious reasons be
Rationale nonwithstanding rules are rules
i dot see what u could do tahts malicious
Do you not? I see plenty. Spamming Discord channels, spam creating Discord channels, spamming user's DMs, mass solicitation, mass advertisements, spreading mass malware, among many other
It's all too easy to be flooding Discord with requests with a self bot
u can do all that with bots so i dont see why making self bots not good
no
Someone I used to know used a self-bot to cheat in a server event that involved finding hidden message reactions scattered throughout the server.
Also self-bots break Discord's terms of service.
I don't think discord.py even allows you to connect with a token if the account isn't a bot user anymore.
Trying to implement cogs to no success, getting the error message ModuleNotFoundError: No module named 'cogs' when I run !load test. Any tips?
import discord
import os
import random
import humanize
from discord.ext import commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix = "!", intents = intents, status = discord.Status.online, activity = discord.Activity(type = discord.ActivityType.watching, name = "you sleep"))
@bot.command()
async def load(ctx, extension):
await bot.load_extension(f"cogs.{extension}")
@bot.command()
async def unload(ctx, extension):
await bot.unload_extension(f"cogs.{extension}")
@bot.command()
async def reload(ctx, extension):
await bot.unload_extension(f"cogs.{extension}")
await bot.load_extension(f"cogs.{extension}")
async def load_extensions():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await bot.load_extension(f"cogs.{filename[:-3]}")```
```python
import discord
from discord.ext import commands
class test(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.commands()
async def test(self, ctx):
await ctx.send("Pong")
def setup(bot):
bot.add_cog(test(bot))```
i am doing it
i have self bot for my alt
How would I host a bot if not using something like replit
Can you show us your project directory structure?
Like this?
Are you on VSCode?
Yep
Can you send us a picture of the file structure on the left bar?
That all?
Outline and timeline tabs
Nah
Extension 'cogs.test' raised an error: AttributeError: module 'discord.ext.commands' has no attribute 'commands' but now a folder called __pycache__ appeared in the cogs folder so I take it that's some progress
Yeah that's supposed to happen
@commands.commands() should be @command.command() (the 2nd command shouldn't be plural)
Yeah just fixed it
Extension 'cogs.test' raised an error: TypeError: object NoneType can't be used in 'await' expression
Should be
async def setup(...):
await ...
setup() was made into an async function in discord.py v2
Running !load test gives white text RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited bot.add_cog(test(bot)) RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Then if I run !test I get: Command "test" is not found
await bot.add_cog()
as @sick birch said must be in setup() function
so should be:
async def setup(bot: commands.Bot):
await bot.add_cog(test(bot))
Thats with await bot.add_cog(test(bot))
Idk why it says it was never awaited even tho it says
async def setup(bot):
await bot.add_cog(test(bot))```
run this
I don't see the await statement
Yeah its fixed now
Now its just giving me Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
its obvious error
error code: 50013 means that you don't have permission to perform that action.
Okay apparently it needs admin perms to send text messages, sure. But yeah its working now, thanks guys <3
the point is to know what are you doing
if you understand we are good!
đ
How do I see when someone's an event host discord.py
What

Wdym
Like who created an event?
The get_scheduled_event method I think works for that.
^ ye u use that object to retrieve what is shown in those docs
help pls
code:
@bot.tree.command(name="new_enemy")
@app_commands.describe(enemy_name = "NAME")
async def new_enemy(interaction: discord.Interaction, enemy_name: str):
embed = discord.Embed(
title="Enemy name",
description="the enemy name",
colour = discord.Colour.blue()
)
channel = bot.get_channel(1069621174184722534)
embed.add_field(name="name", value=enemy_name, inline=False)
await interaction.response.send_message(f"{await channel.send(embed=embed)}")```
it works but this shows whenever i run the command which i didnt want
What is your goal here
Why are you calling channel.send and then putting it in an fstring and passing that to send_message
my goal is to remove this
im sending it to other channel
logs
Why are you using send_message then?
idk i saw it in yt i think its for the slash command
But you don't want to send a message to the channel the command was used in right
yep
Making a giveaway system and I got the reactions and embed working, it's just I don't know why my bot isnt editing the giveaway message and making a new message about who won the giveaway. Here is the code: ```@bot.command()
async def giveaway(ctx, name:str, winners:int, time:str):
# convert time, with my amazing maths!!!
if 'd' in time:
time = int(time.strip('d')) * 24 * 3600
elif 'h' in time:
time = int(time.strip('h')) * 3600
elif 's' in time:
time = int(time.strip('s'))
else:
await ctx.send("Invalid time format. Use 'd' for days, 'h' for hours and 's' for seconds.")
return
seconds = time
embed = discord.Embed(title=f"{name} Giveaway", description=f"{winners} winner(s) can win! Time left: {seconds} seconds.", color=0x00ff00)
message = await ctx.send(embed=embed)
await message.add_reaction('đ')
await asyncio.sleep(time)
users = await message.reactions[0].users().flatten()
users.remove(bot.user)
winners_list = random.sample(users, winners)
winners_text = "\n".join([f"<@{user.id}>" for user in winners_list])
embed.add_field(name="Winners:", value=winners_text, inline=False)
await message.edit(embed=embed)
await ctx.send(f"And the winners of the {name} giveaway are... {winners_text}! Congratulations!")```
If anyone can help thank you.
Maybe your bot's script is closing before the gw ends?
maybe I am unsure.
Try putting some small times like 5 secs or something
users method returns an async generator in discord.py 2
Anyone here who can help me get my discord bot hosted on aws
#discord-bots message
this link is broken
I want low ms with my bot. I already get 40ms ping
i want 20ms
It's probably your internet problem, if u running the bot on your local system
Mate...
I use pebblehost to host my bot and get 40ms ping
Apparently AWS has the fastest servers
Digital Ocean what do i pick
i mean you can just run it in a droplet
can someone help me, not super familiar with discord bots on python, just learning. I know other programming languages though
my bot is connecting to the server and showing up as online but it won't respond to commands
import discord
import os #for token
#Connect to discord client
#This creates a connection instance.
client = discord.Client()
#registering an event
@client.event
#called when the bot is ready to be used
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
#checking if the user came from the bot
if message.author == client.user:
return
if message.content.startswith('$hello'):
send message to channel
await message.channel.send('Hello!')
try:
client.run(os.getenv("TOKEN"))
except discord.HTTPException as e:
if e.status == 429:
print("The Discord servers denied the connection for making too many requests")
print("Get help from https://stackoverflow.com/questions/66724687/in-discord-py-how-to-solve-the-error-for-toomanyrequests")
else:
raise e
my_secret = os.environ['TOKEN']
client.run(my_secret)
Trying to save an attachment as a text file, then read the text file... but I'm getting a UnicodeDecode error. The file is all english, and all normal symbols.
Traceback (most recent call last):
File "C:\Users\main\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\commands.py", line 850, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
File "C:\Users\main\Downloads\Personal Stuff\Bots\Fate of the System\bot.py", line 447, in locate
f = await openedfile.read()
File "C:\Users\main\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\aiofiles\threadpool\utils.py", line 45, in method
return (yield from self._loop.run_in_executor(self._executor, cb))
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\concurrent\futures\thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 733: character maps to <undefined>
The code:
await text.save(file_directory)
async with aif.open(file_directory, 'rt') as openedfile:
f = await openedfile.read() # <- Error Line
Add
await client.process_commands(message)
to the end of your on_message event
thanks
so like this?
@client.event
async def on_message(message):
await bot.process_commands(message)
#checking if the user came from the bot
if message.author == client.user:
return
if message.content.startswith('$hello'):
#send message to channel
await message.channel.send('Hello!')
Should work
other than forgetting to comment something out
Oh wait, you're putting bot there, put client
^
mh, probably there's a problem with the mode
The mode is read text no?
btw rt is the default mode
Yea, I have a habit of specifying anyway ^^;
what the fuck is up with the indentation in this language OMG
The indentation is great imo
makes it look neat af
are you sure that the file doesn't contains unknown symbols for the text mode?
I want to pull my hair out give me brackets
Python is love, Python is life
Yup
I come from languages with brackets. this is such a pain
And use discord.ext.commands.Bot if you want to create prefix commands
I pasted your code in nexus and its giving me an indentation error
The only thing I can think of is that the file is saved with the txt extension but actually it isn't a txt file
@client.event
async def on_message(message):
await client.process_commands(message)
#checking if the user came from the bot
if message.author == client.user:
return
if message.content.startswith('$hello'):
#send message to channel
await message.channel.send('Hello!')
@frail rock, try this?
It opens, reads, and other programs treat it as such though...
They're using Client
ah, then idk what's happening
There's no process_commands
hold on, it worked. was just throwing an "indentation error"
Yeah still not responding though
It's been workin for me, but if you have another way then shoot
shouldn't the process commands go at the end of the function?
I'll go to general help, thanks for trying though!
.
btw you're using discord.Client right?
yes?
then this won't work
I don't know I just started using python for bots lmao. i do javascript normally.
how do I make it respond?
to get started you should use discord.ext.commands.Bot if you want prefix commands
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
think I will just go back to javascript
I thought python would be super simple for this
Python is pretty simple imo
You canât just dive in head first you need to understand what youâre writing
yeah i am a comp sci student but I don't work with python regularily
It is if you know what you're doing
I am familiar with many other languages just not python
I wanted to give it a go because I really like python but I don't have formal understanding of the syntax
Then use one of the other languages you are familiar with lol
You definitely want to know more than the syntax to try and make a bot
yeah I have watched like a video or two but I don't fully know how the library works
if there's like documentation that might help
thanks
How do you use slash commands in cog files?
@commands.command()
async def test(self, ctx):
await ctx.send("Pong")```
!d discord.app_commands.command
Is it the same an in regular?
@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
So this? If so it's not working
@app_commands.command()
async def hello(self, interaction: discord.Interaction):
await interaction.response.send_message("Hello")```
Probably missing somethign aha
account made 1 day ago
What is not working then
Sorry should have sepcidfied, the slash command doesnt appear when i put /hello
Did you sync
Smooth brain moment, how do you sync
Everytime i tried to check if updated commands work i just closed the terminal and reran the bot
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
So like this in the cog file?
@commands.command()
async def sync(self, ctx) -> None:
await ctx.bot.tree.sync(guild = ctx.guild)
await ctx.send("Successfully synced")
print("Successfully synced")```
file = open('test.txt', "r")
content = file.readlines()
for line in content:
text1, text2 = line.strip().split('Ă')
if text2 =="test2":
line.remove()```
how do i remove a line
i mean delete it
@distant python
yo
this
its defined in the txt file
ok good for you i dont know whats in ur text file
no error on that i just want to delte that line
what does this have to do w/ discord.py go to a normal help channel
like this
test1xtest2
1st line
its for my bot only lmao
if u know.......then help me pls
ok but its not related to the discord.py library
ok
therefore its not relevant to this channel
how to add persistent select menu? i have example https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py
but example with buttons, and when i'm doing like in this example i have error
ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout```
Read the error, it explains everything
how do i simply make a cmd with 2 confirmation yes no buttons in side the cmd only and not in any class
That will be one hefty command
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
U can create button using this
the button needs to be have a callback
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
Hey there, can anyone help me?
Just ask
i dont want the class method
@client.command()
async def gen(ctx,amt:int=None):
button1 = Button(label="Confirm", style=discord.ButtonStyle.blurple, emoji=':blue_circle:')
async def button1_callback(interaction):
if interaction.user.id!=ctx.author.id:
return
else:
await refresh(ctx)
button1.callback = button1_callback
button2 = Button(label="Cancel", style=discord.ButtonStyle.blurple, emoji=':blue_circle:')
async def button2_callback(interaction):
if interaction.user.id!=ctx.author.id:
return
else:
break
button2.callback = button2_callback
view = View(timeout=60)
view.add_item(button1)
view.add_item(button2)
await ctx.send("Initiating...Want Refresh?",view=view)```
Why
how do i wait for button click and then do rest of the function
its will be long and complicated
It not, the way you want to do it will just make it unreadable
And the way you have to create button instances, set the callback by setattr, adding to the view is way way longer
Just subclass the view
After I have selected the Administrator Role, the Administrator Role should be checked because it is no longer none
If I run the command again, the embed is correct
Is this Python?
Show the code, we don't know what you did.
discord = OAuth2Session(client_id, token=session['discord_token'])
me = discord.get(base_discord_api_url + '/users/@me')
guild = discord.get(base_discord_api_url + '/users/@me/guilds')
g = []
for gs in guild.json():
gMember = discord.get(base_discord_api_url + f'/users/@me/guilds/{gs["id"]}/member')
g.append(gMember.json())
#discord API```
what i'm trying to do: getting member of a guild (by guild id => https://discord.com/developers/docs/resources/user#get-current-user-guild-member)
what i'm getting instead:
nvm just need a guilds.members.read scope
Integrate your service with Discord â whether it's a bot or a game or whatever your wildest imagination can come up with.
We don't help with self-bots.
noo this is not self bot, just a discord bot dashboard project
Oh, well you know Hikari has an restAPI for this?
no, can tell me more?
btw why rate limited
@cloud dawn @tough lance the code is here btw
!d hikari.api.rest.RESTClient
No documentation found for the requested symbol.
what's the pro n cons using this API (vs regular discord API)
btw i'm using flask too, how to combine this with flask?
yes
Flask with an async API..?
no

i have a dashboard running with fastapi and hikari
flask[async] exists
Bless your soul.
đ lol
combined with HTML too?
send me a bit of its code
https://github.com/sarthhh/anya-web ignore the frontend*
you can find hikari related code in discord_rest.py and fastapi stuff in app.py
If this had migrations it would be a true masterpiece.
is it a bug in which bot react's twice?
Sounds like a feature.
i mean
Fr tough; check task manager, your bot is likely running twice.
Did you use any CTRL+ commands?
yea
ic
HTML with no CSS or SCSS?
That's like Pizza with no Cheese
bootstrap was pretty much all i needed, i used it's cdn url for that
and inline css at some places
Can anyone help me please
I need discord bot help can u respond me in the channel #1069965715626537063
how can i fully close a bot and not get an error because when i do any of these:
await client.loop.stop()
await client.loop.close()
await client.close()
its shows error:
Cannot close a running event loop
what do i do ?
hey yall
I ran my discord bot code but it returned with the error
AttributeError: module 'discord' has no attribute 'Intents'
maybe you've downloaded an older version
import discord
print(discord.__version__)``` run this to check the version
can somebody help me #databases
what is it?
Import "discord_slash" could not be resolved
import discord
from discord_slash import SlashCommand
from discord.ext import commands
import os
from dotenv import load_dotenv
run pip install --upgrade discord.py to update it @obsidian kindle
I use replit
run poetry update
!d discord.app_commands.CommandTree don't use 3rd party libraries for app commands/components
class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
A mirror package for discord.py. Please install that instead.
I use this one
reinstall discord.py and make sure you don't have a folder named discord or a file named discord.py
use discord.py, not this
literally read this package's description
what is fallback_to_global=True
Why did they publish that package in the first place
it's owned by danny as well, probably just to occupy the discord namespace on pypi
Interesting
i need to replace class xxx(commands.Cog) with this class ?
...
it's not related to cogs
that's how you make slash commands in discord.py
discord_slash is useless as for now
Send the error
Hey @obsidian kindle!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
!pip idna
install this, seems like your poetry is broken
Then send the error
what do I do now
which compiler is the best for discord bots
ill just copy the codes in them and use that instead
what do you recommend
i use vscode
it works fine in that?
any editor will work just fine
except replit XD
replit is bound to python 3.8 by default and bugs often
you can't do much about it if you don't know nix
just copying the code in vscode will work right
apart from installing the other packages
im installing a recommended extension by vscode for python
what
code doesnt run magically with a run button
there's resources required for that
you'll have to install a particular language's compiler for the language's file to run
pip install discord.py
showed an error
pip : The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
- pip install discord.py
python -m pip install
not sure about the command
No module named 'install'
python -m pip install ...
py -m pip install ...
python3 -m pip install ...
python3.<your python version> -m pip install ...
any one of them should work
if they dont then you dont have pip
In python's case, an interpreter/compiler!
^
i was talking about languages in general yeah
I have python
it returned with
ERROR: You must give at least one requirement to install (see "pip help install")
[notice] A new release of pip available: 22.3.1 -> 23.0
replace ... with the package you want to install (discord.py) lol
if you wish
it would work without updating?
bot = commands.Bot(command_prefix='!')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'
this was the error it returned
am I missing something in the code?
!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.
Intents are now required kwarg in new discord.py v2.0
its showing invalid sytax for import discord lol
I should change it to discord.py?
pip install discord.py do this
python -m pip install discord.py
SyntaxError: invalid syntax
pip install discord.py
File "<stdin>", line 1
pip install discord.py
^^^^^^^
SyntaxError: invalid syntax
I had just installed discord
try python3 -m pip install discord.py
python3 -m pip install discord.py
File "<stdin>", line 1
python3 -m pip install discord.py
^^^
SyntaxError: invalid syntax
did u try what @shrewd fjord said with just python -m pip install discord.py
same error
python -m pip install discord.py
File "<stdin>", line 1
python -m pip install discord.py
^^^
SyntaxError: invalid syntax
are u running that in terminal, cmd, or in code
terminal
python print ("hello world!")
its not running ig
python -m pip install discord.py
I did ctrl +c
and did u do it again?
like, just got to the window and press ctrl +c?
python -m pip install discord.py
done
yes then rerun that
did it work?
python print ("hello world!")
to clarify, you're inside a python interpreter right now, but the commands they're showing you need to be done in the terminal itself
...
^
so pressing control + c leaves that
python -m print ("hello world!")
Unless he changed keybinds đ
well keyboard interrupt doesnt get you out of an interactive interpreter, its usually ctrl+D or ctrl+Z
its showing requirements already satisfied
I just opened up a new terminal and used that
then discord.py is installed
can u send a screenshot
syntax error means your python code has a syntax error, not that you have a missing library
A screenshot of the code could help
Discord isnt defined hmm
oh the code is giving syntax error
Oh god
?
||pls say thats not replit|| xD
that snippet is showing linter warnings, but not exactly a syntax error...
its not replit
do you have multiple versions of python installed?
^, it would be red
yes
thank the lord
then why
I had the same problem
is it showing the syntax error
I couldnt fix it so I just moved to pycharm lol
@obsidian kindle use a venv
what?
||pycharm is peak||
Can u show ur file structure?
virtual environment
python -m venv env
It's going to create virtual env for u
And on env folder u can install all following libraries
!venv
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)
Then, to activate the new virtual environment:
Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate
Packages can then be installed to the virtual environment using pip, as normal.
For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.
Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.
Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
it is not a syntax error, its indicating that the python environment that vscode has selected doesnt have the modules installed - if you click the Python version on the bottom right of vscode you should see a list of python versions, have you made sure its selected the same python that you installed discord.py to?
^ ur interpreter will be installed here, and all of ur libs. Everything is enclosed, so u wont get issues with it not being recognized.
yes it is selected to the same python version
what is the actual error that shows up when you try to run your code?
Hm gud ques
bot = commands.Bot(command_prefix='!')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'
so the modules are correctly installed, you just need to fix the intents
^
after doing this
intents are correct tho
u need to pass em in with a kwarg
!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.
here







