#discord-bots
1 messages · Page 1119 of 1
constructor is for classes not functions....
and what is that argument naming
i think he ment parameters or function signature
why am riding consturctor as destruct 😭
reading*
Riding
same. this is where i get banned.

Well anyway.
imagine having a clean mind
Okimii, how’s your wrapper going
Literally 2022 rn and you're on the internet. Idk what you expect.
For discord
oh i stopped making it, now im learning rust
bro same 😳
how do i set permission for a certain user on a channel
good video
hax
daily does of internet is a lovely channel
help
!d discord.TextChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
@slate swan ^
now i need to get all channels in a category
!d discord.CategoryChannel.channels
property channels```
Returns the channels that are under this category.
These are sorted by the official Discord UI, which places voice channels below the text channels.
I struggle so hard with these.
Hello
Can anybody provide example of mute-tempmute command code please?
I can't figure out how to add duration
I installed discord.py directly from github without using pip, is it okay? and thx <33
Is there a way to check how many messages a user has posted that contain images/videos?
For timeout
from datetime import datetime, timedelta
await member.timeout(duration=timedelta(hours=3))
# for until
await member.timeout(until=datetime(...)) # you need to construct the datetime object or get it somehow```
This does not work on dpy 1.7 in case you are using it.
If you asked for concrete temporal mute with assigning role that's more complicated
Hey @mellow mauve!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
With tracking yes, with fetching it's a bad idea
Hey @mellow mauve!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Hey @mellow mauve!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
how would i make discord.py dm the user?
No, I have a mute command, but I want to make it perma/temp on choose
Eh alright
So you gotta make a database in which you will store the unmute times for users and insert a new row when a user is muted, next make a loop that would fetch the users whose unmute time has already come and unmute them.
Sqlite is suitable for this case. Make a table with users ids column and the timestamp. For making a loop use @tasks.loop
same bout ban
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
im actually using github template for it
is there a way to execute a command via a webhook or even read a webhook?
editing and learning
If you don't know about databases then make a dict and use json / pickle to serialise it although it is discouraged and you better learn about databases
tho idk if it has database
It doesn't
Your command has nothing to do with what I have suggested actually
The logic is mostly done outside
I use this one
https://github.com/AlexFlipnote/discord_bot.py
🍺 A simple discord bot that helps you getting started within discord.py - GitHub - AlexFlipnote/discord_bot.py: 🍺 A simple discord bot that helps you getting started within discord.py
So um you are copypasting the code and editing values or smth
That's not learning
How would i make python DM The user?
and googling what does each command do
Get a user object and invoke send method on it like
user = bot.get_user(123456789012345678)
await user.send("Hello")```
The 123456789012345678 Would be the ID right?
That's good only if you know required basics well enough
I know basics
like basics of basics
beginner level of python
Yeah but sometimes you are able to access user/member object without id yk like ctx.author
The required basics for discord bots are at least OOP and functional programming
I fucking hate OOP
I failed exam
I'm getting discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'bot' is not defined
Cause you don't understand it or smth
Show me how your command looks like
Yes. Plus my uni uses it's own laggy af program
I don't understand how to work with .h
i dont fucking know but we use it
yeah
How is that related to python
oh fuck thats c++
What’s up with the incorrect typehints?
client.get_user in your case
What do you mean by this?
so, google is my best option here
I mean the library is literally OOP based
and observing code
ctx is in fact an instance of commands.Context, not str, and your function returns void, not str
I'm also getting discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'client' is not defined
And yeah function names in python start with small letter
Also why are you using get_user?
You already have the member object
It’s like going from member object to ID back to member object
To be honest with you, i know the simple part of discord.py.
Because he ignored this
Though I’m still confused on those incorrect typehints, maybe they didn’t read the documentation?
No idea how could they think of typehinting ctx as str and making a command "return" something
Well, forget about that, how do i make it dm the user?
Yours should already do that ignoring the glaring problems
@sick birch btw congrats on project lead
I'm getting an error
Thank you! I’m quite excited to do more haha
..
Haven't been in this server for a while cause went to making a game with unity
The error speaks for itself, did you create a bot instance?
Ah, well glad to have you back then!
yes i did.
Nah I am not really back lol
At least someone is glad tho lol
Yes it is.
I also tried using client.change_presence() when the bot was ready and it returned the same error
Your code is like
client = commands.Bot(...)
@client.command()
async def cmd(ctx):
...```
right?
Yes.
I can't really think of anything besides typos
Try renaming client to bot, it's considered a good practice and may fix some stuff
Alright.
Right click -> refactor -> rename
Nope, same error but 'bot' is not defined.
Also do you have python extension and the interpreter installed and configured? Pretty sure variable should light up with light blue color
And how you code looks now?
Eh wait what is this indent
i've spent way too long messing around with this dumb code, someone else put it to use pls https://pastebin.com/4WskBixJ
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Is it indented or it is just visual indent
I mean like are there spaces right before async def
It is in a class.
Guess that's why you have issues
The bot is inside the class.
Alright.
And use cogs, not common classes
It's a bad idea just to put many commands into some empty class just for organisation purpose
Cogs are recommended
Okay, now i'm getting discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'
Failed to get user by that ID
user = bot.get_user(ctx.author.id)
As mentioned above, you can send the message to a user who invoked the command with ctx.author.send
The user is ctx.author in this case
OOP 😀
Alright that works, thank you very much for the help.
Bad idea? Could you elaborate a little
Users send a lot of messages, now imagine multiple users sending messages, then finally imagine a guild with 1k+ members
You would get ratelimited very quickly with fetches
an error which has nothing to do with dpy and means that amout is None
async def мут(self, ctx, member: discord.Member, amout: str = None, *, reason: str = None):
Mute command for perma and temp at the same time
I hope you did <prefix>мут @wild spoke 2
?
if none = perma
what
it should for like that
show whole code
if no mute time amount is set, then mute is perma
I found it on russian stackoverflow
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
copypasted to my with renaming variables
not the entire
lemme show entire mute code
oh its text
one moment
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
also I noticed that it does not remove mute role
any suggestions besides opening "Python for dummies"?
check_priv doesn't exist?
Anyone know an self-hostable python FAQ bots using dropdowns and buttons?
why bot.run(token) is giving me RuntimeError: Event loop is closed?
may someone help me please?
That’s probably more fit if you coded it up yourself
Probably invalid token
im sure its not but im using discord v2 and im new to it
so...
nvm that was turned off xD
thx anyways <33
Can someone help me with an adding roles command in a bot, it's not working, also the ban command appears to not be working
"not working" doesn't really help. Are you getting any tracebacks? what is the output you're getting vs the output you're expecting?
If only we could have the bot use “not working” as a trigger word and say that everytime someone says it…
ya
webhook = await message.channel.create_webhook(name=message.author.display_name, avatar=message.author.avatar.url)
await webhook.send(message.content)
await webhook.delete()
getting error TypeError: startswith first arg must be str or a tuple of str, not bytes
You sure the error isn’t somewhere else?
I'm trying to get it to add a role but it's giving me "bot object has no attribute 'add_role'"
File "C:\Users\Asus_pc\PycharmProjects\VxBot\main.py", line 51, in on_message
webhook = await message.channel.create_webhook(name=message.author.display_name, avatar=message.author.avatar.url)
File "C:\Users\Asus_pc\PycharmProjects\VxBot\venv\lib\site-packages\discord\channel.py", line 563, in create_webhook
avatar = utils._bytes_to_base64_data(avatar) # type: ignore
File "C:\Users\Asus_pc\PycharmProjects\VxBot\venv\lib\site-packages\discord\utils.py", line 523, in _bytes_to_base64_data
mime = _get_mime_type_for_image(data)
File "C:\Users\Asus_pc\PycharmProjects\VxBot\venv\lib\site-packages\discord\utils.py", line 509, in _get_mime_type_for_image
if data.startswith(b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"):
TypeError: startswith first arg must be str or a tuple of str, not bytes
but now it's just saying that await is invalid syntax
you need a Member object
One second lemmie take a pic
I'm trying to get it to add the role "gumi-red" (ignore the name it's for a bird server)
you .add_roles to user (or ctx.me if you want to add roles to the bot), pass_context kwarg is also deprecated
oh it's add_roles not add_role
I am an idiot and didn't look hard enough at the guide
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
How do I fix the await error tho
?
Its not letting me run it
traceback?
Its just doing tbus
Also the banning doesn't work it just says ban command not found
cause you're doing commands.command and you're outside of a cog, it should be client.command
I don't see commands.command
well the error screen doesn't seem very helpful, do you have a terminal or somewhere in which a traceback is printed?
There's no traceback or anything
it's the first line of the screenshot you sent me
what IDE are you using?
oh that's for the ban
oops lemmie fix that
The python IDLE (if that's what you are asking)
yikes
Is there vsc for Ubuntu? Lemmie check
open your terminal, head over to the directory in which your file is located, and run python3.x your_file.py
yikes again
Gonna do that 😅
The version of Ubuntu I was on was 20.04 and it comes pre-installed with python so I should do that
it should come with both versions though?
wdym
webhook = await message.channel.create_webhook(name=message.author.display_name, avatar=message.author.avatar.url)
await webhook.send(message.content)
await webhook.delete()
Im trying to create a webhook with avatar of the message author
and i get this error TypeError: startswith first arg must be str or a tuple of str, not bytes
python2 and python3 should come pre-installed iirc, you just gotta choose which one to use (which is why you should be running your programs from a terminal)
ah ok
the terminal tells me exactly the mistake I made
ok now it's telling me that module discord not found
yikes again😂
What on earth did I do wrong this time
nothing im just joking
avatar kwargs should be bytes, Asset.url returns a string
you probably installed dpy on python 2.0, you gotta install it on python 3.0
hikari moment
start_poll.description = start_poll.__doc__
I tried pip and it said it's already installed
python3.x -m pip install ...
Wait the IDLE shell is on 3.8.10
After fixing a dumb error now it's saying name 'get' is not defined
traceback?
How to make a bot a speaker in the stage channel?
So that he automatically logs in as a speaker, and not do it manually
get() is not required
well, you don't have a function called get, however I'm pretty sure you just want discord.utils.get
just discord.utils.get()
Message object has no attribute server now
guild, not server
^
Servers have different meaning outside the context of discord and in that of software development
You mash them together (discord API) and you have a naming problem
Bot object has no attribute add_roles
member.add_role
Why are some add role and some add roles
Perhaps check documentation?
there's no add role
!d discord.Member.add_role
No documentation found for the requested symbol.
Bot doesn't have an add_role method
Thought so
you need a Member object
its add_roles which can take more than 1 role arguments to add role
http.add_role handles the requests part
I’d like to emphasize can, just because it can don’t feel like you have to
You can very well use add roles with only one role
ofcourse you can
, just saying in case you wanna add more than one!
cause I've seen people using for loops for adding multiple roles, which is kinda bad
Yup, it’s just some people may look for both a add_role and add_roles without knowing they’re both in one
thats why one should use an ide/editor with autocomplete/linter 😩
And typehint everything you can properly
this but i fixed it so it runs
or do i have to add every role to the bot
nono thats not needed until your bot's top role is above those roles and bot has manage_roles permissions
im still waiting for the conclusion of the admins
@sacred tendon
me on my way to ping mina: 
yea... thats what i did
and the bot spits out an error saying role not found
show your code and how you run the command on Discord
is there a way to tell my bot/code to loop x amount of times? im trying to test a counter and i dont want to stack a ton of += 1 to the test code :p
async def role (ctx, user: discord.Member, role: discord.Role): role = (discord.utils.get(ctx.message.guild.roles, name=Gumi_Red)) await discord.Member.add_roles(ctx.message.author, role) await ctx.send(f"{ctx.author.name} has been given a role")
(role i used to test was Gumi_Red)
why are you using role = utils.get?
you already have the role object from the command argument
lemmie try running it w/o
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
count = x
alr ty
oop it runs without the role = line
it still dosent give the role with a space in it tho
how did you run the command on Discord
{prefix}role {member @} {role}
like i did .role @sacred tendon Chirps Yellow (this is for a bird server and im trying to test the color roles)
@slate swan
since you don't have a 'consume rest' argument and you're not setting the role's name in between quotes, the converter will only search for the role Chirps
as i said, .command @member "role name"
you need the " "
remove_roles instead of add_roles
and you can check if the member has it using if Role in Member.roles
do i put that before or after the current code
you wanna check before adding the role right
yea
after adding the remove thing; argument of type 'property' is not iterable
how do i get an answer without pinging
how do i get the last message sent by te bot in a server?
!d discord.Member.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.10)") 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") permissions to use this.
Examples
Usage...
basically that, but with your bot
was the property thing being weird because i used if and else wrong (idk if i did)
code?
!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.10)") 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") permissions to use this.
Examples
Usage...
Member.history will return the DM history
hmmm
async def role (ctx, user: discord.Member, role: discord.Role): if role in discord.Member.roles: await discord.Member.remove_roles(ctx.message.author, role) await ctx.send(f"{ctx.author.name} has been removed from a role") else: await discord.Member.add_roles(ctx.message.author, role) await ctx.send(f"{ctx.author.name} has been given a role")
you need an instance of discord.Member, not the class' property
how do i fix idk how
Replace all discord.Member with user
hmmmm alright
that did not work
it just spat out user not defined
Code pls
i just changed everything that said discord.Member to user
Code!
I can't help without code
u didn't replaced
is there guild.history?
whats member.history?
What the
leave the typehint of user as discord.Member
whats typehint
Yes
is there guild.history?
no
whats member.history?
message history in DMs, sorry, you should check out TextChannel.history
And await user.remove_roles(rold)
oh alright thanks
!d discord.Member.remove_roles
await remove_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s from this member.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the removed [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
This?
Yes
Listen
Change inside code of the () to role
Cuz u have already did user.add_role
I gtg sry
now its just "unknown role"
Guys is there any good dictionary api that i can use for making a word meaning command?
uh oh the cpu is running at 88 degrees i should fix that
@fading marlin something like this?```py
async for message in channel.history(after=datetime.datetime(year=2022, month=4, day=1))
yes
is the datetime part correct too?
yep
aight thanks
@fading marlin it doesnt seem to work :/
@client.command()
@commands.is_owner()
async def leave(ctx):
for channel in ctx.guild.channels:
async for message in channel.history(after=datetime.datetime(year=2022, month=4, day=1)):
if message.author == client.user:
await ctx.send("True")
break
else:
```its like the channel history part doesnt work at all
theres no response
Async Python wrapper for the freeDictionaryAPI (https://dictionaryapi.dev/) - GitHub - Ay-355/asyncdictionary: Async Python wrapper for the freeDictionaryAPI (https://dictionaryapi.dev/)
Oxford dictionary has a free api too which you might use
i've been stuck on something really simple that i should have figured out ages ago and it's driving me insane
more tedious tbh
@fading marlin where are you 😭
i mean yeah, you don't really need a complete library just to make requests to a site for getting meaning for some word
@stone palm what you trying to do
lib already filters out data 4 u
!pypi PyDictionary
thats sync
hmm, it works for me?
howww
im trying to see if the bot has sent any message after april 1st
in the server
does it send a message for you
yeah
when i use print statements it doesnt print anything after the channel history line
does your bot have the proper permissions?
wouldnt it show an error if it didnt have permissions
you could have an error handler 🤷
but i dont
it has permissions
thats just a py [ entry.get("definition" ) for entry in response.json().get("meanings")] converted into a list of objects tho lol.
Hello my names sam
hello sam
bruh
Idk how to sign up for it
Can I be a mod
I tried but i not found the sign up link
The Oxford Dictionaries API gives you access to our world-renowned dictionary data, including definitions, translations, synonyms, and audio pronunciations.
you can use the site hay recommended if you don't want the token stuff and do it easily
@slate swan do i need to copy credentials?
imagine coding on phone and not learning python
@rain olive
async def word_info(word):
word = await dictionary.get_word(word) # get a Word object
print(f"Word: {word.word}")
print(f"Phonetic text: {word.phonetics[0].text}")
print(f"Part of Speech:word {word.meanings[0].part_of_speech}")
print(f"Definition: {word.meanings[0].definitions[0].definition}")
print(f"Synonyms: {', '.join(word.meanings[0].definitions[0].synonyms)}")
print(f"Example: {word.meanings[0].definitions[0].example}")
How can I assign synonyms definition examples and other things in a varibable?
Instead of combining the command I'm just gonna make them 2 seperate cmds
your question is basic python?
No
I mean i want to assign definition in a varibable called defi
just do it?
How?
uh you shouldnt be learning python by using d.py this is legit one of the most basic thing...
assigning a variable should literally be the first thing you learn hahahaa
No me learning from YouTube
Ik assigning but i confused here
yikes! look at the official python tutorial instead
Me learn from codewithharry
oh because he uses hindi or whatever right
Yes
And easy to learn
fair enuf, but consider the actual tutorial lol
@client.command()
@commands.is_owner()
async def leave(ctx):
for channel in ctx.guild.channels:
async for message in channel.history(after=datetime.datetime(year=2022, month=4, day=1)):
if message.author == client.user:
await ctx.send("True")
break
else:
```why doesnt this work? theres no response and print statements dont work after the channel history line
Ok so how do I get the bot to default to the command author instead of having to ping (for an addrole/removerole command)
bruh why do I have to install discord.py every day with repl.it? The bot doesn't stay awake for some reason, gets interrupted for updates and then dpy just... goes
replit doesn't keep your python environment, so the libraries installed with pip gets purged
use poetry instead
poetry add git+that GitHub link
poetry add git+https://github.com/Rapptz/discord.py that?
I.
thank you, do I have to do additionnal things like import poetry or whatever?
ctx.author is used to get command author
Make the argument optional member: discord.Member = None
then check if member is none, make it the author
nope, its a shell command
write it in shell, not Console
ok how do I do that I'm pretty new to python so I'm rlly bad
oh ok, it worked anyway so it's cool
!e ```py
def foo(arg = "default argument value"):
print(arg)
foo() # when not provided.
foo("user provided value")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | default argument value
002 | user provided value
what the
ok maybe I should stick to the standard discord bots
if you intend to make a discord bot using python, without learning basic python
ill suggest the same.
Ok fine where do I put that
^
I just wanna get rid of the fact I have to ping or else it'll try to find the role as a member
pythons idle😍
just do discord.Member
btw u can also just add the member name and fetch member with name
I'm trying to just get it so it gets the authors name
So whoever is using the command gets it without having to ping themselfs
Where do I put that
typehint user with discord.Member then inside the function do user = user.name

nice
cuz idk what else is offered for ubuntu
uhh, VSCode and Atom? lol
just use vim
I'm thinking same what do u suggest?
emdsf = discord.Embed(title="dictionary",color=discord.Color.green())
Guys me getting invalid syntax error
Can anyone tell what's wrong in it?
Can you show more code? That line looks fine to me without any context.
async def word_info(word):
word = await dictionary.get_word(word) # get a Word object
wor = word.word
pho = word.phonetics[0].text
spe = word.meanings[0].part_of_speech
defi = word.meanings[0].definitions[0].definition
syno = ', '.join(word.meanings[0].definitions[0].synonyms
emdsf = discord.Embed(title="dictionary",color=discord.Color.green())
emdsf.add_field(name="word", value=wor, inline=False)
emdsf.add_field(name="phonetics text", value=pho, inline=False)
emdsf.add_field(name="part of speech", value=spe, inline=False)
emdsf.add_field(name="definition", value=defi, inline=False)
emdsf.add_field(name="synonyms", value=syno, inline=False)
return emdsf
syno = ', '.join(word.meanings[0].definitions[0].synonyms
Missing a ) at the end there
it's very fun, make sure to write tests too
Thank u
Write tests wdym?
https://github.com/szskill/poll-bot/tree/main/tests which is what i did here
i'm testing the poll & help embed creation function
imagine using @lightbulb.set_help(docstring=True)
i do the same,
but use the inspect Library to get the docstring lmao
don't want to add extra decos 😩
then... no difference
👍
wait, inspect? can't you just do __doc__?
plugins/help.py line 54
description=desc + t.cast(str, inspect.getdoc(command.callback)),```
how about command.callback.__doc__
.
ow wait i didn't use the command lmao
!e ```py
import inspect
def foo():
"""a cool function
multiple lines
"""
...
print(foo.doc)
print(inspect.getdoc(foo))
eh
sarth you failed 2 times😭
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | a cool function
002 | multiple lines
003 |
004 | a cool function
005 | multiple lines
you see the reason
i accidentally made code that can draw stuff
bro
hey wait does anyone know how to make bot.run async
im on 2% battery rn
fair
bot.start
less goo
bot.run() is a synchronous version of bot.start()
can finally start fastapi and hikari
override it into an async function if you mean in hikari
tyty all
class Bot(GatewayBot):
async def run():
# do your async stuf
super().run()
forgot self but ykwim
why would you want to make it a coroutine? to use the coroutine object or
😭
What
That's stupid
but .run is blocking
idk most of the time you can just use hikari.StartingEvent/StartedEvent they get triggered once in a lifetime
How do you intend on calling that coroutine?
am not doing it, am answering it.
im pretty sure making async wouldnt do a difference
asyncio.run?
That's a bad answer
elaborate how?
Yes, but bot.run() also calls that. You can't create two event loops, that's messed up
i'm trying to run uvicorn.run and bot.start() concurrently
can i ask for help with my bot in here or is that not allowed?
problem is uvicorn's run function is blocking
you can create multiple event loops...
i have made a music bot but i get this info thing and it doenst work anymore 2022-06-25 07:23:26 INFO discord.player Preparing to terminate ffmpeg process 34588. 2022-06-25 07:23:26 INFO discord.player ffmpeg process 34588 has not terminated. Waiting to terminate... 2022-06-25 07:23:26 INFO discord.player ffmpeg process 34588 should have terminated with a return code of 1. this is my code https://pastebin.com/WRwzB8xq
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
that doesn't matter, it's still correct code in response to the question
You will get very confusing errors very fast
No it is not
ok bb
how can i make the run method async? thats basically it
tho start is the actual deal
Uh don't use run, use .start()
uvicorn, to run FastAPI
Why would you make it async?
but problem is fixed, uvicorn.Server(uvicorn.Config(app=web_app, port=3000)).serve() is solution
ask borrow lmao
fair
to run web server and bot concurrently
Why would you make it async?
Heh?
https://www.uvicorn.org/#config-and-server-instances
Check the second example
The lightning-fast ASGI server.
yeah I saw it
_ _
i have made a music bot but i get this info thing and it doenst work anymore error [youtube] QxYdBvB8sOY: Downloading webpage 985104597242773505 [2022-06-25 07:45:51] [INFO ] discord.player: Preparing to terminate ffmpeg process 37580. [2022-06-25 07:45:51] [INFO ] discord.player: ffmpeg process 37580 has not terminated. Waiting to terminate... [2022-06-25 07:45:51] [INFO ] discord.player: ffmpeg process 37580 should have terminated with a return code of 1. this is my code https://pastebin.com/WRwzB8xq
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. 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;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
until is a positional-only argument, this wont work
it's not okay
if some class is named shop, that is the error
uh?
i think i've been awake too long
how do i fix it 💀
u fix the class
look at how close it keeps the line lengths
either move the command name to the decorator using the name kwarg and change the function name or change the name of the view class
can use any characters or strings
u are missing some parameter
bro
no
oh typeerror in call didnt see my bad
How to make to bot show the avatar in event?
Um yeah I forgor
!rule 9
What kind of event and where to show the avatar
on_member_join
Just send an avatar or embed it into an image and send?
!d discord.Member.avatar is what you need anyway
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
!d discord.Member.display_avatar is better tho
property display_avatar```
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
display_avatar gives default in case there is no avatar if u use avatar.url it will return none
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.
#bot-commands
https://paste.pythondiscord.com/hubexefabe
only the 3rd button is sent
mb
Try changing there callback method names( not sure)
mhm k
you're right Sparky

Oh 👍
👋
everybody here slaps each other too much 😔 rude
elif value == "Ban" or "B":
embed = discord.Embed(title="🔨 Ban", description="Służy do banowania użytkowników.", color=0xffffff)
embed.add_field(name="📕 Użycie:", value='`.ban <@użytkownik> <powód>`')
embed.add_field(name="📖 Przykład użycia:", value='`.ban @człowiek spam`')
embed.add_field(name="🗂 Kategoria:", value="Moderacja")
embed.add_field(name="🚨 Potrzebna permisje:", value ="Banowanie członków")
embed.add_field(name="💾 Dodatkowe informacje:", value = "Brak.")
embed.add_field(name="🔠 Inne sposoby wpisania komendy:", value = "`.b`")
await ctx.send(embed=embed)
elif value == "Ogłoś" or "Oglos" or "O":
embed = discord.Embed(title="📢 Ogłoś", description="Służy do wysyłania wiadomości na #📢-ogłoszenia.", color=0xffffff)
embed.add_field(name="📕 Użycie:", value='`.ogłoś <ogłoszenie>`')
embed.add_field(name="📖 Przykład użycia:", value='`.ogłoś coś tam ważnego`')
embed.add_field(name="🗂 Kategoria:", value="Ogłoszenia")
embed.add_field(name="🚨 Potrzebna permisje:", value ="Zarządzanie kanałami")
embed.add_field(name="💾 Dodatkowe informacje:", value = "Możesz pisać jakiej chcesz długości wiadomości póki nie będziesz miał/a limitu od discorda.")
embed.add_field(name="🔠 Inne sposoby wpisania komendy:", value = "`.oglos`, `.o`")
await ctx.send(embed=embed)
when i write .pomoc ogłoś bot send to me what it should be .pomoc ban
i don't have error
👋
👋 👋 👋
*3
^3
I'm sure mine hits 4 times harder
ap broke
ap?
it should be 5 times so it maintains the rhythm
arithmetic progression
1,3,5,7 cd=2
I uhhh
nvm i did too much math💀
I got holidays, so I'm not even tryna process it
lmao
is danny a pharmacist or what?
biologically active
who knows he might be switching professions
YES
fr?
I am actually not a Discord employee. In fact, I'm not even a professional programmer. In reality, I'm a medical professional who works at my local hospital
I wanna cri so bad, I think I should become a shitty fortune teller or smth
yall didnt know that?
i didn't know that👀
u will be a great fortune teller apparently
respects to danny🙏
Guys any command idea for me?
i'll give you a challenge
send "4" to the user 😎
Dm?
yes
Easy
it's so hard not even NASA engineers can solve it
Let me amke command
I'll send here
@bot.event()
async def on_message(message):
if message.content.start_with("dm"):
await bot.send_message("4")
@dusky pine
ban the user if they send "hi"
Weird 😬
💀
this doesn't send dm also as far as i know it's not send_message any more
nope
wrong
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=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` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. 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://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.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://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.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://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
^
message.author returns a member👀
Yes hard give me more challenge?
This time I will not fail
tic tac toe game using buttons
Hi
hi among us
.. ok
i think it's there in one of the git examples by danny

can't argue even tho it's ||racist||
that's racist though
😅
u change to a anime pfp as well then let sparky have a go
what is going on?
Pfp fight
yeah, sparky called my pfp a "black monkey"
I installed Discord, but if I write import Discord it doesn't work
👀 .
which IDE do you use?
And sz called my pfp among us
what is a IDE
i mean, thats not wrong...
the place where u write and run ur code
software would be a better term than place
ok, pycharm installs a venv by default, so u might have to install discord there, or tell pycharm to use the global environment
😠 😡
It doesn't work
what did you try?
I used the global environment
run ur code and send a screenshot
wait
Traceback (most recent call last):
File "/home/ayoub/anaconda3/envs/discord/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1330, in invoke
await ctx.command.invoke(ctx)
File "/home/ayoub/anaconda3/envs/discord/lib/python3.10/site-packages/discord/ext/commands/core.py", line 995, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/ayoub/anaconda3/envs/discord/lib/python3.10/site-packages/discord/ext/commands/core.py", line 209, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: DiscordServerError: 503 Service Unavailable (error code: 0): no healthy upstream
someone knows what all this mean?
i don't know error handling at all :(
Everybody hates my pfp 😔
whyyy
server error
it's a whitu smonng us char in the space
i dont
||put|| ||an|| ||anime|| ||picture||
is there a simple way to handle it please? I'm kinda urged with this one
||n|| ||e|| ||v|| ||e|| ||r||
much respect
you cant do anything about it unless it's occurring nevertheless
tf is a kiddo boomer
Idk
same question but we dont talk about it
..
hello 👋 ded chat
sparky
spawky 🥺 👉👈
.uwuify sparky
Here is it, behind the black is my name and my token
i'm not dave shut up
imagine hiding your name 😔
mmmh... basically it's a function that loops through all a channel messages to verify if they're NSFW, and also loops through embeds.
since u said this is a server issue, maybe i should add a timer in my loop?
just a tiny time.sleep(0.2) for example?
ur running ur code inside the venv, right click on run, go to edit configuration then select the global env
oh
wont matter since ratelimits with the discord api are dynamic, does it only error when you run that specific code?
well it loops through messages but stops at a certain moment
Yes?
or just click on terminal and install discord there, dont do the global intepreter thing
...........?
Oh wait i think i know where it comes from
I installed it
uwu
No command named "uwuify" found
@lament depot has it
no, click on that terminal and install
i know i know
sure?
i saw eivl use it
here @paper sluice
huh? weird, it should open it in the venv for u
@commands.Cog.listener
async def on_message(self,m):
if m.content == "uwu":
exit()
weird
ew one letter variable names
ew, wont work
FINE
ryuga go and play 😔
What's ew in that I name my var like
dfg, skf, wll
💀
bad coding practice
ik
do this type venv/Scripts/activate && pip install discord.py
learn how to write clean code or I WILL COME TO YOUR HOUSE AT 3AM 🤯 😱
okay i will try
cmon not scary
your code is practically unreadable
Fair enough my bot is not open source 😂
with what i should open the activate thing
even if it isn't
ahem you guys can move to #editors-ides?
you're having troubles with the venv
the two conversations about venv and clean code are not related to editors/ides

wasnt talking about clean code but nvm
OK so
Clean code
so uhhh
can someone send PR to fix the only issue in my discord bot
yeah, it's best tool to keep your code clean
what's the issue about?
help command?
hikari-lightbulb ohmi god
yes, make sure to write tests for the help embed
or i will come to your house
okay that part is optional i'll write it
eh im too lazy, I'm not doing it
same
Wdym by write test
x^69 + y^420 = help command
💀
assert 2 + 2 == "help command"
member.activity
do i have to import smth for it
no, do you know python...
you shouldn't be asking such a question if you're making a discord bot 😩
how do i check every users activity
for what purpose
automaticzally
on command then
ok,
for member in ctx.guild.members:
...
oohhh
then you check member.activity.name
it will output a string
so you could have if member.activity.name == "custom invite here": ...
thank u
np
await ctx.author.add_roles(role)
do i have to put role id in ()
or in ("")
@rain olive
wot's the issue?
a role object
role = ctx.guild.get_role(id)
probably
you can either provide a discord.Role object there, just like Hay said ( without the await),
or simpleadd_role(discord.Object(id=id)), both work.
oooh
fyi go and read the docs whenever u have issues with parameters and their types
usually the docs have the most accurate info
RuntimeWarning: Enable tracemalloc to get the object allocation traceback``` how do i fix that?
need someone to write good help cmd https://github.com/szskill/poll-bot/
Guys what's use of this package
import re
I saw in one bot on GitHub
regex
its not wirking
elif message.author == message.author:
mwm = message.author
inv = ['dis']
role = discord.utils.get(message.guild.roles, name="Image perms")
for activity in mwm.activities:
if isinstance(activity, discord.CustomActivity): #checking activity is a custom activity
print(activity)
if activityName == any(word in activityName for word in inv):
if role in message.author.roles:
continue
else:
await message.author.add_roles(923323634334973982)
elif activityName != any(word in activityName for word in inv):
if role in message.author.roles:
await message.author.remove_roles(923323634334973982)
else:
continue
else:
continue
help
please
you planning to do more stuff in the bot other than what it already has?
wdym
yeah planing to add more, don't know much about hikari/lighbulb yet
will you be using plugins? they are like cogs in dpy ( functionality)
yeah
love cogs
okay now that I think about it i think it's weird to have tests and a web server for just a poll bot
mhm, why even write tests for bots
just use eval and stuff to test your code 💀
cause you can actually trigger events and commands in an eval
eval 💀
async def fetch_ids(ctx, channel, message):
if message.embeds:
text = re.findall('[0-9]+', message.embeds[0].description)
for i in text:
if not req.search_id(i) and not req.search(i):
req.add_id(i)
text = re.findall('[0-9]+', message.content)
if text:
for i in text:
if not req.search_id(i) and not req.search(i):
req.add_id(i)
I can't get why this doesn't work ! It's driving me crazy !
When I replace req.add_id(i) by print('Added to database') this works fine, doesn't come from the conditions.
Then it says Unique constraint error for adding... I don't get it
ctx.send(embed=embed)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
how do i fix that?
you forgot await
await ctx.send(...)
is it allowed to write nsfw messages?
i want to ask something but it has something to do with nsfw
send it
@commands.command()
async def marryrate(self,ctx,user: discord.Member):
a = ctx.author
b = user
resp = requests.get(f"https://loverapi.herokuapp.com/api/v1/calculate?personA={a}&personB={b}")
resos = json.loads(resp.text)
rate = resos["result"]
message = resos["message"]
hg = discord.Embed(title="Marry rate", description=f"Marry rate-{rate} | Message-{message}",color=discord.Color.red())
await ctx.send(embed=hg)
Guys how to fix this error?
instead of json.loads(resp) it's supposed to be json.loads(resp.text)
Can anybody tell am I doing this right? I want to connect my database
async def main():
async with aiohttp.ClientSession() as session:
asyncpg.create_pool(dsn='TOKEN')
async with self:
self.session = session
await super().start(config.TOKEN, reconnect=True)
Thanks
It's giving this error now
Can u pls send the error instead of screenshot
It's the error tho
Error is key error : 'result'
Here
There is no key named result
It's there
Can u show
try a = ctx.author.name and b = user.name
Ok
do you guys know a hentai api?
nhentai has an api
here's a wrapper
thank youu
It worked thanks
Btw i posted my bot code on GitHub once check it out
Guys is there any good translate api that i can use in my discord bot command?
Use google translate
!pypi deep_translator
It's bad i tried
This looks cool?
use deepl ig then
what's the formatting for having thats ascii box in an embed which works on phone as well like 3*` followed by __
source = auto
Do it means that it auto detects?
yes
sheesh that's some good stuff
if u don't wanna get rate limited btw use translate_batch()
why did I read that as "bitch" 😭
translate this you bitch
@tasks.loop()
async def status_role(seconds=15):
guild = client.get_guild(921366728016011324)
role = get(guild.roles, name='Image perms')
for member in guild.members:
if member.activities and 'j' in member.activities[0].name.lower():
await member.add_roles(921720262217568268)
print("gave role to " + member)
elif member.activities and 'fi' not in member.activities[0].name.lower():
await member.remove_roles(921720262217568268)
print("removed role")
its not'
givinf orle
.add_roles(role)
Thanks for help i am an translate command
Thanks a lot
thats what i did'
u put role id
@commands.command()
async def translate(self,ctx,lang:str,text):
translated = GoogleTranslator(source='auto', target=lang).translate(text)
trans = discord.Embed(title=f"Translator | Translated to {lang}", description=translated,color=discord.Color.green())
await ctx.send(embed=trans)
My translate command :)
Thanks Asher
my eyeball is hard rn
thats exactly what i did
btw it takes only 2000 characters at once
and that's exactly what you should not do
just replace I'd with role
oooooooooooooooooooooooooooooooohhhhhhhhhhhhhhhhhhhh
i told you a few hrs ago
and deep_translator is sync
How to make it written when a person joined the server? such as month and year.
!d discord.Member.joined_at
An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
So I've just setup a new venv and installed all the packages needed but I'm getting an error that the asyncpg package has a undefined symbol _PyGen_send and I'm not sure why since I have a global environment that has all the same requirements and that's working. The error I'm getting is 2022-06-25T12:01:50: ImportError: /home/testing/env/lib/python3.10/site-packages/asyncpg/protocol/protocol.cpython-310-x86_64-linux-gnu.so: undefined symbol: _PyGen_Send okay so I updated my requiremnts.txt and tried again and now I'm getting a new error2022-06-25T12:15:10: TypeError: shield() got an unexpected keyword argument 'loop' full traceback: https://paste.pythondiscord.com/adedalegih, my reqs.txt: https://paste.pythondiscord.com/umavokutos
@tasks.loop(seconds=15)
async def status_roles():
guild = client.get_guild(921366728016011324)
role = get(guild.roles, name='Image perms')
for member in guild.members:
if member.activities and 'discofloofi' in member.activities[0].name.lower():
await member.add_roles(role)
print("gave role to " + member)
elif member.activities and 'disfloofi' not in member.activities[0].name.lower():
await member.remove_roles(role)
print("removed role")
Ik
No ig
doesnt works still
Google translator?
Nah you dont need to await it
help
what
help me
^
oh wait
#bot-commands
that's cool and all, now what
Guys can anyone suggest me a api that i can use in my bot?
discord api

still doesnt work
https://rapidapi.com/hub/
if u want api, search here
How to list all server member id's?
[m.id for m in guild.members]
@tasks.loop(seconds=15)
async def status_roles(ctx):
guild = client.get_guild(921366728016011324)
for member in guild.members:
if member.activities and 'discoloofi' in member.activities[0].name.lower():
await member.add_role(discord.Object(id=921720262217568268)
elif member.activities and 'discordfloofi' not in member.activities[0].name.lower():
await member.remove_role(discord.Object(id=921720262217568268)
Ok sorry for the generic and repetitive question, but where would one start to make a discord bot in python? What library should i use? Is there any guide or something?
File "main.py", line 61
elif member.activities and 'discorfloofi' not in member.activities[0].name.lower():
^
SyntaxError: invalid syntax
discord.py is a good place to start
its get started section and docs are pretty awesome
discord.py and always discord.py
new pfp sparky hi
Hi 😔
Wasn’t it discontinued or something though?
who told u
u forgot to close parens in
await member.add_role(discord.Object(id=921720262217568268)
above the elif
NameError: name 'guild' is not defined
Ye it was but they continued it due to public pressure
public pressure



hm?
