#discord-bots
1 messages · Page 94 of 1
get_channelattempts to get the channel object from it's internal cache. If it's not in there, it returns None. You can fix it by doing something like this to fetch the channel with an API call if it's not in the cache
answer_channel = interaction.client.get_channel(ac) or await interaction.client.fetch_channel(ac)
- Me, about 20 minutes ago
I tried fetch channel
Fixed! Thank you so much!
?
what do you mean exactly by this
so say
they send like this
a
A
A
if it goes past 3 lines in 1 message
itll delete their message
hmm not sure. get the message_content and see how its returned. cause i don't know if the message will actually be returned like that if getting from the bot
@weary flume ```py
if message.content.count("\n") > 3:
await mesasge.author.ban("D: D: D: D:")
ily
mesasge🤔
and reason is a kwarg
Yeah, I excluded that just in case they were one of those people who copy pastes stuff
I mean, the mesage one was
what's the difference between *args and **kwargs
How can I store a username change if a member changes their username on discord? (if my bot is in the same guild as them it should store it into a db, but i need a way to detect the username change)
!args-kwargs
*args and **kwargs
These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.
Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.
Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.
Use cases
• Decorators (see !tags decorators)
• Inheritance (overriding methods)
• Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
• Flexibility (writing functions that behave like dict() or print())
See !tags positional-keyword for information about positional and keyword arguments
!positional
Positional vs. Keyword arguments
Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.
Example
>>> print('Hello', 'world!', sep=', ')
Hello, world!
The first two strings 'Hello' and world!' are positional arguments.
The sep=', ' is a keyword argument.
Note
A keyword argument can be passed positionally in some cases.
def sum(a, b=1):
return a + b
sum(1, b=5)
sum(1, 5) # same as above
Somtimes this is forced, in the case of the pow() function.
The reverse is also true:
>>> def foo(a, b):
... print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1
More info
• Keyword only arguments
• Positional only arguments
• !tags param-arg (Parameters vs. Arguments)
somtimes,
Note
A keyword argument can be passed positionally in some cases.
def sum(a, b=1):
return a + b
sum(1, b=5)
sum(1, 5) # same as above
A keyword argument can be passed positionally in some cases
But they're showing a positional argument with a default value🤔
good catch
actually wait
I think it's just showing you can use kwargs in place of positional arguments
The wording is a bit confusing but the point stands
what?
Hey!
When trying to run my bot, the bot goes online
But also returns this error
discord.errors.HTTPException: 400 Bad Request (error code: 30034): Max number of daily application command creates has been reached (200)
And some of my commands are missing...
How would i fix it
You can only sync your app commands 200/d iirc
sounds gay
Unnecessary comment that makes no sense
any way around it?
Wait a day
Don't try to workaround rate limits
They're there for a reason and should be respected
sounds like a girl on there period 
What?
Trying to circumvent ratelimits would probably just get you banned
Well not really a "rate limit"
But a "rate limit" to app commands, if you will
You could've circumvented the whole problem to begin with if you only synced commands when you needed
How does a ratelimit to avoid API abuse have any relation with a females menstruation?

Can i make it so when someone types the other persons id in chat it adds them into a private channel?
I'm sorry to bother you, but If I tell you an idea for a bot, would you be able to generalize some instructions on how to do it?
I might be able to
So in a channel, if someone sends a message, I create 2 reactions, thumbs up and thumbsdown.
In one week if the thumbs ups don't get to above 5 in a week, they are deleted.
I know how to do the reactions, I'm just not sure how to check how many of a reaction is clicked, and also I'm not able to know if it's been a week or not.
!d discord.utils.sleep_until
await discord.utils.sleep_until(when, result=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sleep until a specified time.
If the time supplied is in the past this function will yield instantly.
New in version 1.3.
or asyncio.sleep()
Okay so like this:
When message is recieved --> Add 2 reactions, await asyncio.sleep(week_in_seconds) # Do check here
This would work?
Looks good
Just quick thing, would this halt every single.... would this halt the program, or would it thread? (Would it run asynchronously so they don't interfere)
asyncio
It's async, so nothing is blocked
async :)
Okay, thank you so much!
Been awhile since I messed around with coding. Made a decent bot with discord.py and now trying to rewrite it using nextcord. Anyone know of a nextcord server?
Why would you want to rewrite it, if you've already got it in discord.py?
Because it's been acting up and I thought it might have to do with .py being discontinued
discord.py is not discontinued
it's strong as ever 
It would stop the execution of that async function and then yield to the event loop so the event loop can execute other scheduled tasks for concurrency
Okay.
give it 6 months
from when? Now? maybe tomorrow? 6 months from when it went active again? 
That's to be seen
Interesting to see you here Preocts. From now
How do I count how many people reacted to a reaction?
!d discord.Message.reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
like this? print(message.reactions.count(':thumbsup:'))
if you wanted to get the first emoji reaction count, it'd just be print(message.reactions[0].count)
GM, is it possible to create an interaction with a spoiler tag? ex: As soon as the member clicks on the spoiler tag and displays the word, the discord bot prints that word in the terminal.
Does anyone know, where can I find more about Translator class? - https://discordpy.readthedocs.io/en/latest/interactions/api.html#translations
What want to know about it?
Because I think that’s all there is that’s written down in the docs
Hey im very very knew to python can you help me with somthing rq?
I may be able to. Have to go soon tho
its quick
why does every single python file i oopen close
open\
even the ones made by other people
So does the code not run?
I have no idea it opens the window then closes instantly
Hey @modern pecan!
It looks like you tried to attach file type(s) that we do not allow (.mkv). 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.
bruh
see
Like it dosent really show on the video
but a little windows appears
You tried to run a python file with pythons interpreter but the file raised an error and closed
Hey!
i am trying to make an add currency command for my economy system
Code:
https://hastebin.com/tugejejagi.py
But i want it to return if the user getting the currency isn't authed in settings, how would I do that?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Aren't you already doing that? You're returning of the target id is in the json
i tried, but even though it says that
i am authed and i tried adding stuff to myself it just returned telling me run the ecoclaim command
i think it has something to do with the way the .json file is formatted
Code:
{
"authed": [
"295499172994351105",
"",
"755155481458114630"
]
}
So you need to check if it's in data["authed"] not in data
how owuld i do that
JSON as a db and blockingio😬
idk its just supposed to be a simple thing
sqlite with a asynchronous driver is quite easy as well and it's good because it's actually intended to store allot of data and commit CRUD operations
i know...
Then why are you not using a db if you know its advantages?
My point still stands
ok
doing a lot for 3 people 👀
it would be better to switch before you end up growing it
might turn into a bigger project, might as well start off right
what i was planning to do
when the bot is finally done and shit
with more that a couple people
If you want a large crowd of people using your bots database i wouldnt recommend sqlite either
im not that popular lmao
Depends what you define on a "large crowd of people"

what do you use/rec?
It would depend on the application
It would still depend on abstractions and usage
just an overall database say storing a guild and all the info that could apply to the bot being nearly custom
Would depend on how much data you're storing and how you want to store it
say ~50 guilds, each guild containing around 15 different variables ie id’s or bools for toggles and how storing doesn’t matter
sqlite or mongodb or sqlalchemy are good with an asynchronous driver
Depending on the growth of the data you can go for something like postgresql which is great
For 50 guilds you'll still be fine with just a json doc. Sqlite is the light weight database option, and is easier to migrate to something like postgres later if you do need to scale
json is bad, just use sqlite
If you use something like aiofiles and JSON it wouldnt really be an issue, just quite a hassle, you just would have a few limitations and no basic integrity but can be implemented, if you want a JSON like database you can always use mongodb but sqlite would be recommended as sqlites purpose is being a lightweight SQL based database and since it's based on SQL you can use the query language for other SQL based databases as you stated, postgresql
My point was that with 50 guilds, it shouldn't matter what you use. It won't bottleneck on it.
unless you plan on writing/reading once every half a second per guild.
And still then... probably not
Well, wouldnt it also depend on how much columns/data you're storing per guild that may cause speed and management related issues?
They mentioned 15 variables, as long as those aren't huge datasets it wont affect anyything
Hello there - I'm new to Discord bots, and I'm curious about what options I could go for with this challenge-
I need a prewritten string to be posted every week - the prewritten string should vary every week, and not have duplicates until it has run through the whole list. 🙂 Any idea where I shouls start?
How would you approach it yourself?
I could give you a possible solution out of the bat, but I don't think it would help you solve something similar in the future :)
I'm entirely new to discord bots, not selecting the items :).
Well, they said it theyre weren't going to be large and/or advanced datastructures, so yeah it wouldnt
So you're good on the getting a new string every week, without showing duplicates?
What library are you using?
I'd probably write a list of strings, and then randomly use an int within range of the indexes to pick one - and then remove the entry from that list, add it to an "used" list, and if the next pick exists in the used one, reselect
I'm totally new to it, so I have no idea what libraries to use for Discord bots 😦
Seems reasonable
I'd just shuffle the list once, and pop the end entry off until it's empty. But yours should work just as well
I can't say I'm super up to date on the libraries these days, but I know discord.py had tasks.loop which is set to run every x amount of time
I wouldn't trust the "x amount of time" to figure out when to post your string, so storing a datetime it should post and constantly checking if it's past that time is a bit more robust
i'm pretty sure loops are just while not client.is_closed
so there isn't any amount of time
Okay, now I just need to know how to automate it and do it regularly.
the best "free hosting" is your own pc
or any spare pc
if you have a raspberry pi even better
help in #help-pear plz
@commands.command()
async def banner(self, ctx, member: discord.Member = None):
if member is None:
member = ctx.author
embed = discord.Embed(
title=f"Test",
color=0x9C84EF
)
embed.set_image(url=member.banner)
await ctx.send(embed=embed)
how to get the banner of a user??
!d discord.Asset.url - get the url from it
property url```
Returns the underlying URL of the asset.
i use sqlite all the way up to like 700 guilds and somehow never had an issue.
and i was constantly accessing the db
That what he said, they are good when you use it with async driver
Only if you have a bank card
hello, mornin!
just got a simple question please... is there a way to test things that i cant as the owner? like i want to test as a simple user or something like that if that simple-user can do something i tried blockin and etc.
to do things like this i use my alt account
oke
and what about making commands in separated files? for ex. welcome.py , ping.py , cls.py and so on..
???
Hey!
I have a command thats supposed to set something in sqlite
Code:
https://hastebin.com/nabalodoge.py
Error:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Cursor' object has no attribute 'ececute'
But my other command that looks simular if not the same doesnt error
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Pretty sure it's cursor.execute and not cursor.ececute
im dumb
I am not able to get the heart overlapping the images in it
You can just copy the original emoji from your client or use the webclient
since it would be a clear png you can use it
Not sure if thats your issue or if it's related to pillow😅
the heart emoji on discord is not a normal image format picture, its a svg so you won't be using that here
I'm pretty sure you just use inspect element and you can just ge the img from their which I've done before?
that's still a svg file
and downloading a png image from internet doesn't hurt anyways
Idk but it saved as a png for me i cant really do it right now though
¯_(ツ)_/¯
All i know is i used it for guild emojis a long time ago
again guild emojis are images, not vectorized web formats
reason why default emojis don't have a url
i know?
sure.
ok
It is very easy to get PNG versions of any twemoji asset, they are all public on GitHub after all
Emoji for everyone. https://twemoji.twitter.com/. Contribute to twitter/twemoji development by creating an account on GitHub.
as image or as link?
also what lib are you using?
LINK
Is it because the person you're doing it to has no banner image
they have
What's the error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'url'
@dull terrace
Dude... It's exactly what I said it was
member.banner = None
I'm telling you, it's not there, whether you have the wrong member or something
And your bot is in a server with the person you're getting None for member.banner?
yes'
Have you tried directly copying their id, fetching the user and then printing banner URL?
Then you can determine if it's something in your code or something probably with permissions
you need to fetch the user in order to get their banner
!d discord.User.banner
property banner```
Returns the user’s banner asset, if available.
New in version 2.0.
Note
This information is only available via [`Client.fetch_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.fetch_user "discord.Client.fetch_user").
read the note
help
discord.os?
I haven't seen that qualifier for literally any other attribute. Weird.
And why would it only work for one person and not the other with his code 
the users in discord.py's cache are derived from member payloads ( which doesn't have banner key )
or maybe discord.py Just doesn't save that, im unsure
how to check if a object is a discord.Member object or not
Why would you want to do that 8ster?
First way that pops into my head is doing hasattr(object, "username")
cause I have user2 object and if it's a member object then it must have a #discriminator
isinstance(..., discord.Member)
okay thanks
Yeah is instance is much better, I forgot about that 
Your hasattr wouldn't have worked anyways
username doesn't exist in discord.py it's name and since Member inherits fields from it's underlying user it has the same attributes and more
So hasattr(..., "name") would've worked on Member and User
But they aren't the same thing, as member has more than user which isn't exactly ideal
😤
Hi
well, that is because andy is very smart in the aspect of developing. so when andy explains something to someone who doesnt have the same knowledge, it may be looked at as confusing because andy is explaining something with the assumption it can be understood as simply as he/she understands the topic. so yeah it creates confusion. thats why you ask more and more. the more you ask the more you know. dont walk away misunderstanding the topic because one explanation didnt give you the knowledge needed. im sure andy would have been willing to break down the explanation.
is there a way to fetch all the data from a database and display the results in one embed
Hmm, I've used isinstance before but yes Andy a smart dude 
this depends on the database that you are using and whether if you are using a library that handles calls to the database, btw that's not really related with discord Bots
I end up doing janky things because I don't think about things for long enough
no, I got the data, its just displaying the output in one embed rather that multiple embeds, I use aiosqlite btw
Exception has occurred: TypeError
BotBase.init() missing 1 required keyword-only argument: 'intents'
File "C:\Users###\Desktop####\Discord_Bot.py", line 5, in <module>
bot = commands.Bot(command_prefix = settings['prefix'])
try using
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="$", intents=intents)
if its nextcord
u also have to enable the intent permissions in the discord developer portal for the bot
hmm
are u using nextcord or discord.py?
replace nextcord with discord
Ok
under applications > bot enable the intent privileges
how are you currently building your embeds?
staff_role = 1024293502621843456
ticket_main_channel_overides = {
interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),
interaction.user : discord.PermissionOverwrite(read_messages=True, send_messages=True),
interaction.guild.staff_role : discord.PermissionOverwrite(read_messages=True, send_messages=True)}
ticket_main_channel = await interaction.guild.create_text_channel(f"{interaction.user.name}'s channel", overwrites=ticket_main_channel_overides)
Says guild has no staff role
how do i define it ??
Why the creation of a reference if its only going to be used twice?
not really sure it came along with the new update
kinda surprised me too
what
creating different embeds for each data
Making a reference of Intents and using it twice isnt a part of any update?
that's irrilevant, could you share your code, idk where the problem of your current code is
if I'm correct intents are used to give privileges to the bot
ye sure
its below
@bot.command()
async def display_bdays(ctx):
async with aiosqlite.connect("bday.db") as db:
async with db.cursor() as cursor:
await cursor.execute("SELECT * FROM bd")
data = await cursor.fetchall()
for row in data:
bdem2 = nextcord.Embed(title="ALL BDAYS", description="blank")
bdem2.add_field(name="Name:", value=row[1], inline=False)
bdem2.add_field(name="Month:", value=row[2], inline=False)
bdem2.add_field(name="Date:", value=row[3], inline=False)
await ctx.channel.send(embed=bdem2)
the main part
As per best practices, you should keep one database connection in the bot
Instead of connecting every time in each command or event or whatever
he's saying that there's no reason to create a variable since you're not changing the intent values against the values provided by the classmethod, so you can directly pass the object without creating a variable
like
bot = commands.Bot(..., intents=discord.Intents.all())
That's not my point, my point is you made a reference
intents = discord.Intents.all()
and made its reference count into 1 and then referenced it in your bots constructor __init__ making its reference count into 2, over just passing the value
oh ye, u can do that too
This is a damn nice feature
you should have an empty list and append embed objects to that list, then you should pass that list as kwarg embeds=list of a send method
!d nextcord.ext.commands.Context.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` or `embeds` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.File "nextcord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.File "nextcord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Embed "nextcord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Embed "nextcord.Embed") objects. **Specifying both parameters will lead to an exception**.
Python bot when nextcord docs requested: Wait, what the fuck is that
I have never used nextcord, luckily the structure has not changed
Yea, they all use discord.py docs
import asyncio, websockets, discord
from discord.ext import commands
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())
async def handler(websocket, path):
await websocket.send("hello")
ws = websockets.serve(handler, "localhost", 8000)
@bot.command()
async def crash(ctx):
print("detected crash command")
# await ws.send("hello") doesnt work
bot.run("bot token")
asyncio.get_event_loop().run_until_complete(ws)
asyncio.get_event_loop().run_forever()
```So basically i want to send a message to websocket when a command is fired
everything under bot.run is not executed when the bot is online
!d discord.ext.commands.Bot.run
run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., root_logger=False)```
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.start "discord.ext.commands.Bot.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.connect "discord.ext.commands.Bot.connect") + [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login").
This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.
Warning
This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
Read the warning
what can i do about that?
you should create a main coroutine function and calls inside it await bot.start(...) and the other functions, then you could call the main function with the asyncio module
ok i will try that.
Guys is there any UI improvement i should do in my game?
Maybe I'm stupid, but I don't know how to make it work. Usage exmaples would be amazing
i have a discord bot, and i'm using sys.exit() to close it because await client.close() takes ages and sometimes just does nothing, how do i stop it from giving the error raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed
i don't mean like fix the error cuz i know what it is, i just mean catch it and not print the damn error every time
@bot.command()
async def ship(ctx, user1=None, user2=None):
if isinstance(user1, discord.Member):```
how to get the user1 name if it's a discord.Member object?
user1 and user2 will always be a string or None here. never a Member
I wanna allow the user to input a string or a member object
HELP
HELP
How often can I change a bot’s name and picture before it times me out?
you shouldn't have to check if they're both Member objects
you should just use a slashcommand tbh
@app_commands.command(name = "ship")
async def _ship(interaction: discord.Interaction, m1: discord.Member, m2: discord.Member) -> None:
...
Maybe?
user1: discord.Member
that way there's no way they could supply a non member argument
can someone help me with my bot
then how will I check if it's a member object?
there's no need to
how do i do that the bot will watch the number of members?
because it will always be a member object in that case
!d discord.Guild.member_count
property member_count```
Returns the member count if available.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be specified.
Changed in version 2.0: Now returns an `Optional[int]`.
I wanna allow the user to enter strings too
why?
you'll have a list
tysm,m
of essentially every member in the entire guild
so there's no need to enter a string of any kind
@severe rampart??
here's an example @pulsar solstice ^
OH
if the user wants to enter John and the john in not in the server then?
no for that you have to loop through all the servers that the bot is in and add the member counts together @slate swan
nono
the bot is only in one server
then you need to fetch that guild object and get the member_count of that guild
i don't... how would you ship with someone who is not in the server? what do you mean lol
bruh pls
I want this feature in my bot
@tasks.loop(seconds=120)
async def change_status():
guild = bot.get_guild(246691336776843265)
membercount = guild.member_count
await bot.change_presence(status=discord.Status.dnd, activity=discord.Activity(type=discord.ActivityType.watching, name="{} members".format(membercount)))```
pls
YES. that's exactly it!
yw :)
why is it not working
did you wait 120 seconds?
use typing.Union[discord.Member, str] for typehinting and then check your isinstance stuff that you were doing earlier
will discord.Member, str really work?
if yes then that's just common sense!!!
Can anyone tell me how often I can change my Bot’s username and picture before timing out?
@severe rampart waited and still dowsnt work
typing.Union[discord.Member, str]
yes
typing is undefined
import it, its an inbuilt python module...
import typing
oh
if you're using py3.10 you can do ```py
discord.Member | str
can someone help with that
bc it doesnt work
did you start the task?
wdym
That task loop isn't going to start on its own... You need to start it
by doing py main.py
What
how to start it
That's how you run a python script
You need to start the task loop in your python code
how
!d discord.ext.tasks.Loop.start
start(*args, **kwargs)```
Starts the internal task in the event loop.
change_status would be the Loop for you
where do i put it
@tasks.loop(seconds=120) async def start(*args, **kwargs): guild = bot.get_guild(246691336776843265) membercount = guild.member_count await bot.change_presence(status=discord.Status.dnd, activity=discord.Activity(type=discord.ActivityType.watching, name="{} members".format(membercount)))
In your code, where you want to start the task
like this?
Ok i give up @slate swan you explain
Or i am terrible at explaining
can u help me w that
I am also bad at explaining :\
Let's say this is a loop
@tasks.loop(...)
async def some_loop(*args, **kwargs):
...
Now you gotta use start to start the loop in on_ready or setup_hook
some_loop.start()
I tried helping a kid and ended up writing his whole code that was understandable from him.
oh
i think i got it
so it would be like that -
@tasks.loop(seconds=120)
async def change_status(*args, **kwargs):
guild = bot.get_guild(246691336776843265)
membercount = guild.member_count
await bot.change_presence(status=discord.Status.dnd, activity=discord.Activity(type=discord.ActivityType.watching, name="{} members".format(membercount)))
change_status.start()```
@naive briar?
I'd suggest that you'll have to wait until the bot is ready before starting the loop
ill see
off its not working
You have to start the loop for the loop to work. By putting change_status.start() in the loop will do nothing
so i dont rlly understand how
ok i will try
working!
thank u sm.
awesome
can someone help me with verify system
GM, Does anyone have any idea how I can make it so that after X time the discord buttons are removed using await button.delete() ?
nvm I solved the issue myself thanks anyway
if I put a type hint of string and if the user enters a member then will the member object change into a str
whats the new avatar_url code ?
Discord.py literally changes it every freaking week wtf!!!
I am sick of this
ye same it worked like a few days ago and now it broke
i found it guys
it just like this embed.set_thumbnail(url=user.display_avatar) this is for embed btw
so I made a bot on replit, and it's basically webscraper bot that sends message when it find what it's looking for, and for me it's manga update, and I want it run couple of times every hour, but it only checks it once when I start up the code. How can I change that?
Is it possible to get the message id of a message when a button attached to the message gets pressed?
the interaction you receive has a .message attribute where you can get the ID there, or alternatively you can store the message as an attribute of your view subclass when you send it (that way you dont have to wait for a button press): py view = MyView() view.message = await ctx.send(..., view=view)
Ok thank you!
just .avatar for member
how can I send messages on schedule?
is there a way to grab a users pfp as a png?
hello, I watched a video to add a drop-down menu to my bot, but by putting the module imports, it does not work 😦
doed anyone knows how to install buckettype?
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
msg = '**Still on cooldown**, please try again in {:.2f}s'.format(error.retry_after)
await ctx.send(msg)
@bot.command(aliases=["H"])
@commands.cooldown(1,30,commands.BucketType.user)
async def h(ctx, *,message='No Reason ! ❌'):```
it says
also i did
from discord.ext.commands import cooldown, BucketType
do you have a command named as commands?
Yes
Why does it say Choose wisely.?
This action is irrevocable! Why they are saying it?
Also should I create a application and bot on my main discord account or create an alt account?
does discord.app_commands.context_menu need the member and message intents? because I wanted to create one but it just doesn't show up
yeah so you already imported BucketType from commands so you only do BucketType.user
Just classic discord humor
You can continue and make the bot
what lib are you using?
discord.py 2.0.1
They take upto 2 hours to sync. Discord Limitations @wispy sequoia
I used copy global to
I ofc use a test guild
Did u specify the guilds kwarg?
?
R u registering those as global commands?
Hey guys, is there away to send the modal using a command? All examples I found is that it lets you to click on a button
yes
console.log....?
Registering global commands take upto 2 hours
Registering commands in certain guilds by specifying the guilds kwarg is instant
it's just a test context menu
Context menus don’t work inside cogs
yes tysm!
It’s doable though. I had to do it for one of my PRs
Hang on a sec let me find it
python-discord/bot#2269
@wispy sequoia here I had to create a context menu from within a cog
where is it, I just see the discussion
Go to the changes files tab
can someone help me with verify system?
Right about here
wtf why?
dpy giving us a slice of bread and telling us to make a sandwich
lmfaooooo
this is why i never used dpy lol. so behind on things i get that they left but still.
light mode 😭
does anyone knows why is it like that?
thats the code -
@bot.event
async def on_member_join(member):
channel = bot.get_channel(1023615552477995080)
background = Editor("pic.png")
profile_image = await load_image_async(str(member.avatar.url))
profile = Editor(profile_image).resize((150, 150)).circle_image()
poppins = Font.poppins(size=50, variant="bold")
poppins_small = Font.poppins(size=20, variant="light")
background.paste(profile, (325, 90))
background.ellipse((325, 90), 150, 150, outline="white",stroke_width=5)
background.text((400, 260), f"Welcome To {member.guild.name}", color="white", font=poppins, align="center")
background.text((400, 325), f"{member.name}#{member.discriminator}", color="white", font=poppins_small, align="center")
file = File(fp=background.image_bytes, filename="pic.png")
await channel.send(f"Hello {member.mention}! Welcome to **{member.guild.name}** Have fun!")
await channel.send(file=file)```
Context menus do not support group contexts (e.g. Cog or Group). This is for a few reasons.
- Within Discord itself, they cannot be bound to a group. There is no such thing as a "sub context menu" right now, and if it exists in the future it probably will not be in the same category as a Group would be.
- If added, the Group and the Cog would need to handle and maintain a mapping of context menus to eventually add back and remove from the tree. This complication and extra space doesn't seem worth it to me, especially considering you can only have 5 context menu commands anyway.
- The context menu would have to store bindings (the self parameter) which is an incredibly complicated thing to do that has been a common source of bugs within the library.
This is kind of ironic but this is one of those things that is actually significantly easier to do yourself rather than the library generalising it to fit to everyone's needs. For example, in a cog you can do the following:
class MyCog(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
self.ctx_menu = app_commands.ContextMenu(
name='Cool Command Name',
callback=self.my_cool_context_menu,
)
self.bot.tree.add_command(self.ctx_menu)
async def cog_unload(self) -> None:
self.bot.tree.remove_command(self.ctx_menu.name, type=self.ctx_menu.type)
# You can add checks too
@app_commands.checks.has_permissions(ban_members=True)
# @app_commads.guilds(12345)
async def my_cool_context_menu(self, interaction: discord.Interaction, message: discord.Message) -> None:
await interaction.response.send_message('hello...')
This lets you manually add the context menu to the bot tree when a cog is created. The Python runtime handles the self binding for you as well, rather than the library.
In this case I think it might be the other libraries making questionable choices. Discord.py's reasoning for this seems logical to me
Hi, is it possible to use selenium with discord's api ?
No, selenium is blocking
Other solution to replace it ?
You could thread it or run on seperate processes
asyncio_tothread ?
Hm?
like the whole tree thing is just mind boggling to me lol. disnake, its literally just @user_command and @slash_command that's it lol. my opinion the reason for the libraries are to make it easier to use the API ?
this
Sure. Though keep in mind with simplicity and abstraction you trade away some control. So there's that to keep in mind
If you want a more simpler, beginner friendly library, or aren't as good with Python, one of the forks may be of use
If you want more control and your bot may be complex, then discord.py may be the library for you
Just weigh their pros and cons with your usecase, as with most technologies in this field
true
Discord.py shouldnt be used for a complex application, especially with its history and codebase
we use it for most of our bots, which are quite complex 😄 especially @unkempt canyon
I already knew you were going to say that, Its complex, yes, The only reason @unkempt canyon doesnt use a private wrapper is because the team probably doesnt want to go through the rewrite and making a wrapper, i'm not saying discord.py is bad abstraction wise, as its codebase isnt the best, while you have large bots like mee6 that use a private wrapper written in python
The things you guys need to do to see whats wrong with an abstraction of the library is probably allot, going from a public method to an internal that has submethods which those submethods have submethods and it keeps going
Hey, does anyone know how to send a message with a discord bot if a minecraft server turns online or offline?
yes
it is against minecraft eula though i believe well my version is
you would create a minecraft account. you create a bot in javascript or python where it would connect to the minecraft server. if connection is successful it sends a webhook request or a message to a discord bot to send to the server
just make a plugin with JDA. Bots like that already exist
Hello, im making a bot and i need a way to save into the database (replit) without preventing "heartbeat" from stopping is there anyway i can save data when the bot disconnects from discord or just regualrly?
would be easier if it wasn't replit
what could i do though?
use an asynchronous database connector
i tried
and..?
thats async and await right?
right
it didnt work
How exactly did it not work?
How are you monitoring heartbeats? You've got logging enabled?
no but i i got in console that the heartbeat wasnt passing though
Hm. If it's async, and it still does that, might just be a replit thing
Even when bot doen't have errors or warnins, is it even possible to find the problem, for example : a for loop who doesn't work as well ?
on_close maybe?
YES THATS IT THANKS
If the bot doesn't have errors or warnings you may have a faulty error handler
I have a dict who get for (key:channel.id, value:link) and i passed in for loop dict.items() to get some scrapped data and send to the specified channel but if i have two links and also two channels, it works only at starts and after that it loops only for the first key of dict
How to solve this ?
um i cant bring the value into on_close anything i can do?
you can bind it to your bot instance
how
if role in after.roles:
print("found role")
beforeactivity = discord.utils.get(before.activities, type=discord.ActivityType.custom)
print('1')
if beforeactivity != afteractivity:
if beforeactivity and afteractivity is not None:
print('2')
if string not in afteractivity.name:
print('3')
try:
print('4')
await after.remove_roles(role, reason=f"Removed {string} from status.")
except:
traceback.print_exc()```
This code works to remove the role when the status is not None but not `string`, but if I completely remove my status, it won't remove the role
found a way made it global.
bot.<var-name> = <value>
don't use globals
making a vanity bot i see
look at my bio. ill help you haha
make a function that checks the users custom status.
ty
and return True or False
@commands.Cog.listener()
async def on_presence_update(self, before, after):
try:
afteractivity = discord.utils.get(after.activities, type=discord.ActivityType.custom)
beforeactivity = discord.utils.get(before.activities, type=discord.ActivityType.custom)
if afteractivity is None:
return
if beforeactivity and beforeactivity.name == afteractivity.name:
return
record = await self.bot.db.fetchrow("SELECT role, channel, string FROM vanity WHERE guild_id = $1", after.guild.id)
if record is None:
return
role, channel, string = record
role = after.guild.get_role(role)
channel = after.guild.get_channel(channel)
if not any([role,channel,string]):
return
if channel and not role:
pass
if role and string:
if afteractivity.name is not None:
if string in afteractivity.name:
try:
await after.add_roles(role, reason=f"Has {string} in status.")
except:
traceback.print_exc()
else:
pass
if channel and role and string:
if beforeactivity != afteractivity:
if beforeactivity and afteractivity is not None:
if string in afteractivity.name:
try:
await after.add_roles(role, reason=f"Has {string} in status.")
await channel.send(embed=discord.Embed(description=f"{self.bot.yes} {after.mention}: You have been given {role.mention} for putting **{string}** in your status.", color=0x303135))
except:traceback.print_exc()
else:
pass
if role in after.roles:
print("found role")
beforeactivity = discord.utils.get(before.activities, type=discord.ActivityType.custom)
print('1')
if beforeactivity != afteractivity:
if beforeactivity and afteractivity is not None:
print('2')
if string not in afteractivity.name:
print('3')
try:
print('4')
await after.remove_roles(role, reason=f"Removed {string} from status.")
except:
traceback.print_exc()
except:
traceback.print_exc()
my code is so bad i can't figure it out
holy lmao
I know there is easier ways, but I don't know how
bare excepts
required_activity = "what to check for here"
for activity in after.activities:
if isinstance(activity, disnake.CustomActivity):
if str(required_activity).lower() in str(activity).lower():
i need to rewrite all of this wanna help me lmfaooo
File "application.py", line 18
REDIRECT_URI = f"{DOMAIN}/discordauth"
^
SyntaxError: invalid syntax
there that's pretty much all you need
do you use presence update or member update
why is this
presence
it works to give the role, but not to take it
make a function with that code return True if they have the required_activity return False if they dont.
then just check if the function is False and the member has the role
and if they do then remove the role
that means i have to rewrite it all 
if role in after.roles:
print("found role")
beforeactivity = discord.utils.get(before.activities, type=discord.ActivityType.custom)
print('1')
if beforeactivity != afteractivity:
if beforeactivity and afteractivity is not None:
print('2')
if string not in afteractivity.name:
print('3')
try:
print('4')
await after.remove_roles(role, reason=f"Removed {string} from status.")```
I just want to figure out how to make it remove if there is no status at all
just check if they have role and if they dont have the activity
thats alot of unnecessary code.
activity = discord.utils.get(after.activities, type=discord.ActivityType.custom)
if str(activity).lower() != string and any(role.id == int(role) for role in after.roles):
await after.remove_roles(role)
@old token
what would activity_check be
yea idk what this did but it broke everything
no error but it wouldn't even give the role
show code
File "/usr/local/lib/python3.5/dist-packages/requests/compat.py", line 11, in <module>
import chardet
ImportError: No module named 'chardet'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "application.py", line 1, in <module>
import requests
File "/usr/local/lib/python3.5/dist-packages/requests/__init__.py", line 45, in <module>
from .exceptions import RequestsDependencyWarning
File "/usr/local/lib/python3.5/dist-packages/requests/exceptions.py", line 9, in <module>
from .compat import JSONDecodeError as CompatJSONDecodeError
File "/usr/local/lib/python3.5/dist-packages/requests/compat.py", line 13, in <module>
import charset_normalizer as chardet
File "/usr/local/lib/python3.5/dist-packages/charset_normalizer/__init__.py", line 24, in <module>
from .api import from_bytes, from_fp, from_path, normalize
File "/usr/local/lib/python3.5/dist-packages/charset_normalizer/api.py", line 71
previous_logger_level: int = logger.level
^
SyntaxError: invalid syntax```
fix
read the error
ImportError: No module named 'chardet'```
oh nice another disnake user
me?
yee
I have stopped making discord bots lol
And when I used to they were made without the help of any wrappers
I think U also need python 3.6+
he does
My library
usage?
Well it was to make it a bit easier to make blocking code non blocking but that got boring so I expanded it to more async related stuff
Ohh
Nicee
😑 Oh... I was like why they are asking such things.
Why am I getting this when it reach await collection.find_one(find)
you sent a screenshot of an internal server error captioned with "fix"
do you really expect someone to know how 😭
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.
@rugged shadow here is the traceback
okay 1s
https://media.discordapp.net/attachments/343944376055103488/1024320945244090408/IMG_20220927_193515.jpg
Guys is there any UI improvement i should do in my game?
r = requests.post(
"{API_ENDPOINT}/oauth2/token",
data=data,
headers=headers
)
@rugged shadow
you forgot the http:// and the f in the fstring
could that be why?
bc the f strings r gone?
ight, ill add them
You should use buttons
If I make a command that recites one line of the verse of a song each second, would it overload the Discord API?
How many messages could it send in a, say, 10 second time frame before getting ratelimited
not overload, it can handle your connection aight
you'll just get ratelimited tho
i dont know
50 per second across all of discord
5 per second per guild
But that's also rule of thumb, I'm sure how they calculate stuff is more complex than that
Yeah there are per-route ratelimits that are private
How can I sync my slash commands to every guild rather than using guild = . . .
Just sync them globally
Ye... how?
Just tree.sync() without passing guild kwarg
!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.
How do I get the error if the bot can’t dm a user inside a command
discord.Forbidden
i know its messed up
discord.ext.commands.errors.MemberNotFound: Member "890131928454410270" not found.
see your parameter definition, anythinf after *will be coverted to a string by dpy
same error
Why are you fetching member? Isn't "member" already a member object?
oh lol
if the member is not in guild it shows the same error
how is it a member then
umm?
if the user isn't in a guild, then how is it supposed to be a member of that guild. why would anyone mention someone like that
or you can simply typehint member as a Union of discord.Member and discord.User and discord.py will do the work for yoh
smh
oh yes
guys
can anyone help me with coding a bot
when i want the bot to answer me how can i make it to happen
You can't send message if the content was None
@naive briar that is my help cmd error
@naive briar i cant send the error pic in your dm
@vagrant crescent
@tacit prairiejust send the code and the error here
!rule 9
you can ask your problems while coding one and people will help with it
Ohhh
Thanks and sorry
Does anyone knows why is it like that
@bot.event
async def on_member_join(member):
channel = bot.get_channel(1023615552477995080)
background = Editor("pic.png")
profile_image = await load_image_async(str(member.avatar.url))
profile = Editor(profile_image).resize((150, 150)).circle_image()
poppins = Font.poppins(size=50, variant="bold")
poppins_small = Font.poppins(size=20, variant="light")
background.paste(profile, (325, 90))
background.ellipse((325, 90), 150, 150, outline="white",stroke_width=5)
background.text((400, 260), f"Welcome To {member.guild.name}", color="white", font=poppins, align="center")
background.text((400, 325), f"{member.name}#{member.discriminator}", color="white", font=poppins_small, align="center")
file = File(fp=background.image_bytes, filename="pic.png")
await channel.send(f"Hello {member.mention}! Welcome to **{member.guild.name}** Have fun!")
await channel.send(file=file)```
Thats the code
whats the issue? the welcome thing?
yo
Yes
Its little there
Its supposed to be in the middle and bigger
the image size is much smaller than that of the background so it appears small. resizing both images to an optimal size would be the fix
How
!d PIL.Image.Image.resize
Image.resize(size, resample=None, box=None, reducing_gap=None)```
Returns a resized copy of this image.
raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'async_generator' object has no attribute 'flatten' how to solve this error in dpy2
@slate swan
Where are you calling .flatten
# before
users = await reaction.users().flatten()
# after
users = [user async for user in reaction.users()]
hi, how to build bot using javascript?
Any good course/guide for discord bots?
docs are the best way to learn for now
how experienced are you with python?
Pretty good with basics. Like the course I am following right now, I am learning bout intermediate stuff.
great
so you first step would be choosing a library for bot development
there's discord.py and it's forks ( disnake, pycord etc...)
and other libraries like hikari
I'd recommend discord.py or hikari
What does Client do?
Client represents your bot in the code
Oh.
https://www.youtube.com/watch?v=SPTfmiYiuokI I am learning from freecodecamp right now.
thats totally outdated
Yes.
Also, they are making bot in replit.
And that's bad, cuz replit files are public
unless you have bought some plans.
yes thats the doc page
here's a nice guide
Yes, looks good.
Thanks!
@slate swan One question.
How will my bot stay online forever?
@slate swan
u need to buy a server
check pins in #965291480992321536
yeah
the user has no avatar
OHH
@slate swan
i did put a pfp now and it still doesnt work
also there r ppl w no pfp so now when they dont have a pfp then the bot will not do that?
you can use display_avatar
!d discord.User.display_avatar
property display_avatar```
Returns the user’s display avatar.
For regular users this is just their default avatar or uploaded avatar.
New in version 2.0.
member.display_avatar.url bru
hello guys
how can i add time duration for kick or bans
i create a bot but i can't find the code for it in discord.py
timestamp=ctx.message.created_at
thanks bro
How do i pass a variable from a button to a Modal in nextcord?
Here is the code: https://pastebin.com/RCvgHNde
Simply pass the "message_id" to the instance you are creating
await interaction.response.send_modal(
Name(message_id)
)
ok and where do i get it in the modal?
You can set the class's variables by using self.varname = var and then get them using self.varname. In your case, that will be self.message_id = message_id
def __init__(self, message_id):
....
self.message_id = message_id
I don't know if I used the words right, but I think it can give you a fair idea
I think i get it ill try
Guys is there any platform which provides free discord bot hosting for like 5-6 months for free?
make sure you call super().init if youre doing something like this ( its for zuuki )
Ik i tried that but get this error now
TypeError: ModMail.__init__() takes 1 positional argument but 2 were given
class ModMail_Response(nextcord.ui.Modal):
def __init__(self, message_id) -> None:
super().__init__(
"ModMail Response",
timeout=900
)
self.question = nextcord.ui.TextInput(
label="What is youre answer?",
min_length=1,
max_length=500,
required=True,
placeholder=f"EE"
)
self.add_item(self.question)
self.message_id = message_id
async def callback(self, interaction: nextcord.Interaction) -> None:
print(self.message_id)
class modmail_button(nextcord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@nextcord.ui.button(
label="Respond",
style=nextcord.ButtonStyle.green,
custom_id="respond:green"
)
async def report_user(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
message_id= interaction.message.id
await interaction.response.send_modal(ModMail(message_id))
here is the code again
you only need to pass the timeout in the init ig
im not sure how nextcord modals work
!d nextcord.ui.Modal
class nextcord.ui.Modal(title, *, timeout=None, custom_id=..., auto_defer=True)```
Represents a Discord modal popup.
This object must be inherited to create a modal within Discord.
New in version 2.0.
Pls tell anyone
seems fine to me
not without a credit card
k thx ill try
I want to use termux but very hard to use
its literally just pkg install python install dependencies and python filename
No the repository thing
It says me respository under maintainence
I prefer termux
It works fine for me 
Get:1 https://mirrors.tuna.tsinghua.edu.cn/termux/science-packages-24 science InRelease [8011 B] Ign:2 https://main.termux-mirror.ml stable InRelease
Ign:3 https://dl.bintray.com/grimler/game-packages-24 games InRelease
Err:4 https://dl.bintray.com/grimler/game-packages-24 games Release
502 Bad Gateway Err:5 https://main.termux-mirror.ml stable Release
Redirection from https to 'http://ww38.main.termux-mirror.ml/dists/stable/Release' is forbidden
Reading package lists... Done E: The repository 'https://dl.bintray.com/grimler/game-packages-24 games Release' does not have a Release file.
N: Metadata integrity can't be verified, repository is disabled now.
N: Possible cause: repository is under maintenance or down (wrong sources.list URL?).
E: The repository 'https://main.termux-mirror.ml stable Release' does not have a Release file.
N: Metadata integrity can't be verified, repository is disabled now.
N: Possible cause: repository is under maintenance or down (wrong sources.list URL?).
I got this error
:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1664375264:f> (10 minutes) (reason: discord_emojis rule: sent 25 emojis in 10s).
The <@&831776746206265384> have been alerted for review.
!unmute 803509687541956648
:incoming_envelope: :ok_hand: pardoned infraction mute for @slate swan.
i just needed help..
We're always watching 👀
Could you reword your question so that it doesnt involve so many emojis? Otherwise our bot will automute you to prevent spam
Okay
:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1664375499:f> (10 minutes) (reason: discord_emojis rule: sent 24 emojis in 10s).
The <@&831776746206265384> have been alerted for review.
To my knowledge, that could happen because you downloaded termux from the play store 
lmao
uhoh
Hey, someone knows how I could do a simple reminder ? :)
!unmute 803509687541956648
@slate swan screenshot the question in another server and post the screenshot here.
:incoming_envelope: :ok_hand: pardoned infraction mute for @slate swan.
Sorry, I'll just paste your message if you dont mind
Is there any way to scrape a site then send it to bot? I wanna send that image as
🟩🟩🟩🟩🟩
🟩🟥🟩🟩🟩
🟩🟥🟩🟩🟩
🟥🟩🟩🟩🟩
🟩🟩🟩🟩🟩
Is it possible?
Well it's possible but is it live edited? What do you have in mind?
What do you mean by live edited?
Well do you want to update the message accordingly?
no
From where would I downloaded then?
Then it is pretty viable. You would just need to use aiohttp then use asyncio.create_task (recommend to use loop) to use beautiful soup 4 (bs4) asynchronous.
ill send u a link in dm because it doesnt show only that diamonds and bombs
or video
Yeah? With beautiful soup 4 (bs4) you can extract that data from a website.
Depending if you need to login of course.
it doesnt require any login
@slate swan Do you code on phone only?
no
As they said in their Wiki
i code on pc too
Well then it's just a matter of what I said above.
"You would just need to use aiohttp then use asyncio.create_task (recommend to use loop) to use beautiful soup 4 (bs4) asynchronous."
i want my bot can kick people without camera in voice channels what should i do ?
!d discord.VoiceState.self_video
Indicates if the user is currently broadcasting video.
I recommend getting the voice channel the iterate over the members, I'd still make a check if the voice state is not None to avoid potential issues.
how to do that? i am begginer and i don't know lots of things in py
I suggest looking into aiohttp and make some basic requests then. Their Docs -> https://docs.aiohttp.org/en/stable/ , are pretty clear so should only take a sec to setup in a command.
geth init --datadir node1 genesis.json
Fdroid not provides terminal .
What?
I can't get terminal like termux in fdroid
Frdroid only shows me some packages
I don't understand what is only shows some packages 🫠
It shows me this
F-Droid is like an app store
You have to download termux from it
Ye
That's because the file doesn't exist in its current directory
How can I run file then?
I even tried cd downloads/ but not worked
Any errors?
It's says
no such file or directory downloads
How can I run files from my internal mobile storage?
Go to storage
I mean by using cd
Ok
It says
no such file or directory storage
What is your current directory?
Hey!
I have a bot event:
Code:
https://hastebin.com/bajolakuku.py
I want it to run after the bot is ready how would i do that?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
You can create a task, dont use requests or time as they block the event loop
import hikari
bot = hikari.GatewayBot(token='removed')
@bot.listen(hikari.GuildMessageCreateEvent)
async def print_message(event):
print(event.content)
bot.run()
``` It's keep on printing `None`, whenever I type something in # general in my test server.
how
Yes, most libraries have an intents abstraction
You can use history but it's limited afaik
how would i create the task?
loop.create_task(coro, *, name=None)```
Schedule the execution of [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) *coro*. Return a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") object.
Third-party event loops can use their own subclass of [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") for interoperability. In this case, the result type is a subclass of [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task").
If the *name* argument is provided and not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").
Changed in version 3.8: Added the *name* parameter.
Took @unkempt canyon a while, i thought it wasnt going to respond kek
This fixed the problem.
Ya
To be honest, I found that from google.
Don't really know what happened...
@tasks.loop(seconds=120)
async def change_status(*args, **kwargs):
guild = bot.get_guild(393401064264564746)
membercount = guild.member_count
await bot.change_presence(status=discord.Status.dnd, activity=discord.Activity(type=discord.ActivityType.watching, name="{} members".format(membercount)))
why is it not working
My bot is a fricking genius
The guild with such ID doesn't exist or is unavailable
thats weird
its the guild id
!d discord.Client.fetch_guild
await fetch_guild(guild_id, /, *, with_counts=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") from an ID.
Note
Using this, you will **not** receive [`Guild.channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.channels "discord.Guild.channels"), [`Guild.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.members "discord.Guild.members"), [`Member.activity`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.activity "discord.Member.activity") and [`Member.voice`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.voice "discord.Member.voice") per [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member").
Note
This method is an API call. For general usage, consider [`get_guild()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_guild "discord.Client.get_guild") instead...
Try this
It might be not in cache as well
where do i put that
He's so smart, he doesn't even know about punctuation.

It's called a period.
?
I never studied grammar sorry
😡
Instead of bot.get_guild(...) you do await bot.fetch_guild(...)
Microsoft blocked 22h2 in Russia but I still downloaded it lmao microsoft go take the L
how can i use the voice client to play a music ?
Is bot in that guild at all
yes
!d discord.Intents.guilds
Whether guild related events are enabled.
This corresponds to the following events...
Are you sure the bot whose token you are authenticating with is in the guild with ID you put to fetch_guild
And what intents do you have enabled
Wtf
Depends on where you are going to play the music from
youtube ?
That's illegal
so is spotify supported ?
What do you recommend
I don't make music bots, but you need a service with public API
Ok so they have it, now explore the endpoints and find out if you can search the song and then stream it
@commands.command(aliases=["img", "g"])
#@commands.cooldown(1, 30, commands.BucketType.user)
async def image(self, ctx, *, query):
try:
api_key = "api"
resource = build("customsearch", "v1", developerKey=api_key).cse()
result = resource.list(q=query, cx="72281f48bb8b04598", searchType='image', safe='active').execute()
class Menu(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
@discord.ui.button(label="next", style=discord.ButtonStyle.grey)
async def nextbutton(self, button: discord.ui.Button, interaction: discord.Interaction):
self.current_p = +1
url = result['items'][self.current_p]['link']
embed = discord.Embed(color=0x303135)
embed.set_image(url=url)
await interaction.response.edit_message(embed=embed)
view = Menu()
current_p = view.current_p
try:
url = result['items'][current_p]['link']
embed = discord.Embed(color=0x303135).set_footer(text="Powered by Google - Safemode: active")
embed.set_image(url=url)
await ctx.send(embed=embed, view=view)
except:
await ctx.send(embed=discord.Embed(description=f"{self.bot.warn} {ctx.message.author}: No **results** found for **{query}**."))
except:
traceback.print_exc()```
```py
current_p = view.current_p
AttributeError: 'Menu' object has no attribute 'current_p'```
idek i guess i'm overlooking it, never used buttons before
type \ just before and emoji to get it's format
yeah
no
oh
just paste this in code
and you will get an emoji
yup
when you send the msg on discord, obv
oh
then how do i make it work
you can also just post the unicode
literally just copy paste the emoji as is from emojipedia
if its custom then yea do that way
guys someone sent me this and its a discord bot
oh
.send("This is my fav. duck - ")```
Hey @faint blade!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
like this ^^
yes i did it
and it doesnt work on discord
because the bot doesn't have the emoji then
those emojis can be directly used in code
yeah
windows key + .
huh no i literally just copy the emoji and paste it lmao
but
this one 
It is from the server
adn it didnt work
if the bot doesn't share and a server where that emoji is then it won't work
that will consume 4-5 seconds more
where are you putting it?
I mean, which field
oh
its animated
so you need to do <a:
oh
tyyy
ill try now
still doesnt work
bot is not having access to that emoji then
