#discord-bots
1 messages · Page 501 of 1
yes? the library i said is for ipc
yes good but the thing is like discord-ext-ipc is good buy it cannot be used for the thing i am trying to do thats why i was asking for ipc and i dont really get what multiprocess.communication is
is it a lib or a module of mutipocess
no i am using quart
Ah
!pypi multiprocess
Well, sorry bro... I haven't made a dashboard till now so I don't have any experience with the same
:c
import disnake
import os
import time
from life_saver import get_crypto_price
from disnake.ext import commands
from crypto_listing import get_crypto_rank
CMC_API_KEY=os.environ.get('CMC')
token=os.environ.get('Discord_crypto_bot_token')
client=commands.Bot(command_prefix='!')
@client.event
async def on_ready():
#await client.change_presence(status=disnake.Status.idle)
print("Hey you I am ready ")
@client.event
async def on_message(message):
if message.content.startswith('!'):
crypto_to_check=message.content.split("!",1)[1].lower()
await message.channel.send(get_crypto_price(crypto_to_check))
if message.content.lower()=='/commands':
await message.channel.send("type / + crypto's name to get the crypto price")
await message.channel.send("for example:\n /bitcoin to get bitcoin's price")
@client.command()
async def rank(ctx,crypto):
await message.channel.send(get_crypto_rank(crypto))
client.run(token)
Hello,I am getting this error:AttributeError: 'Client' object has no attribute 'command'
do you mean commands?
!d discord.ext.commands.Bot.commands
property commands: Set[discord.ext.commands.core.Command[discord.ext.commands.core.CogT, Any, Any]]```
A unique set of commands without aliases that are registered.
@odd pendant plz help
bro shut up
but why
https://stackoverflow.com/a/6921402 look at this
he was helping me out previously and u entered without knowing anything so just shut ur trap
when I added the s I got another error TypeError: 'set' object is not callable
This is not the appropriate channel for this. You may ask in #web-development . This is for Discord bots development and not general discord-related questions.
from discord.ext import commands
bot = commands.Bot(command_prefix = ";")
@bot.command()
async def ping(ctx):
await ctx.send("pong")
bot.run("")``` why does this happen? `module 'discord.ext.commands' has no attribute 'Bot'`
Try updating discord.py.
alright.
its on the latest update
print(discord.__version__)
add this to yr code please
this should print the version
client = commands.Bot(command_prefix = ";")
AttributeError: module 'discord.ext.commands' has no attribute 'Bot'
PS C:\Users\mp420\OneDrive\Desktop\slumsbotpy>
did you enter the token?
of course
HELP
you need to put your bot token, where it says TOKEN
i'm tryna use a env file
remove the ``
i now get this
do you have TOKEN="your discord bot token"
from azlyrics.azlyrics import lyrics
song = input('song:')
artist = input('artist:')
ly = lyrics(artist,song)
for line in ly:
print(line)
i get the input here but then i do that in replit then it show error ```
but i have the required things\
import discord
import os
from azlyrics.azlyrics import artists, songs, artists
from azlyrics.azlyrics import lyrics
client = discord.Client()
@client.event
async def on_ready():
print("we have logged in as{0.user}".format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("$k"):
x=''
args = str(message.content).split(" ")
args.pop(0)
args = " ".join(map(str, args))
args = args.split(",")
wd = lyrics(args[0],args[1])
for line in wd:
x=x+line
await message.channel.send(x)
print(wd)
client.run(os.getenv("TOKEN"))
@outer ridge
wd =
ye how do i fix?
Go to the environment variables
and check if you have your token there
yes it's in there
it work fine here
can you print it please?
try this:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = ";")
@client.command()
async def ping(ctx):
await ctx.send("pong")
client.run("TOKEN HERE")```
without the token
DISCORD_TOKEN="token"
no that's not how you save an environment path
HELP :((
still not working.
On repl.it? what's the error
reinstall dpy
alright,
it work fine
this show the errror
whats the cmd for it btw?
terminal work fine but repil show the error @outer ridge
pip install discord.py
for uninstall
guess
pip uninstall discord.py đ
what error??
i mean it dont work should i run it in vsc or command prompt?
No
how do i save it then
error that it not exist
do py -m pip uninstall discord.py
reinstalled it.
well that's not a really known library
so i doubt anyone has a solution for it
works, tysm đ
just don't use REPL xD as it's a Linux / Unix environment
whats wrong with unix environments
search "env variables" on Start
and then this will pop up
i'm using ubuntu though
@outer ridge
ah damn
that kinda sad
i can use different library suggest be a library for lyrics bot
Just use pyopen('token.env').read() then
mostly people use genius py but i cant understand it tbh
or a way to do it
use a "with" enclosure then
with open('token.env') as token_file:
token = token_file.read()
you still havenât answered my question on whatâs wrong with unix environments
Well, the library probably doesn't work correctly on that platform that REPL uses
I assume so since it works on your computer
also check that REPL is installing the same version of that library
hm so we just guess that itâs the libâs fault
also pls use the commands extension for commands
How do I prevent messages being duplicated?
Also, you can use @client.command() instead of handling it with the on_message event. By using client.command you can just name the function with the command function and it will get triggered when the command is used.
Hm?
like eeeeeeeeeeeeeeeeeeeeeeeeeeeee
client.command wont work in their case right now
so people cant spam like that
theyre using Client not Bot
Hmm
I'd probably check the consecutive letters
I dont know how tho xd
use a collections.Counter
is there any api I need to check
well there is no definite way to classify spam
youâll just have to guess based on character count and occurrence
Wait
since somebody can write a whole paragraph
I have an idea
and it can detect it as spam
so on the message event channel
I can make an variable that says
spam = ["eeeeeeeeeee"]
and more
thatâs too inefficient
you wonât have a list of tens of hardcoded items
well cmon, its just the alpabet
but you could
alphabet*
I could probably try and check if message.content is times 2
which also should work
idk
you can have per-server character limits
@gleaming torrent
def is_spam(string):
consecutive = 0
last_char = ''
for char in string:
if char == last_char:
consecutive += 1
if consecutive >= 6:
return True
last_char = char
return False
I just wrote this, should work
again thatâs not efficient
it's the only way xD
i can have multiple characters in the same sentence
and it is efficient
Well it's functioninh
like this
no, you didn't understand what my code is doing
it has 6 e
it's if their next to each other can't you see that
what
he re re re re re re is fine, heeeeeeeee would be spam
lol
it gives you all the characters
You didn't even read my code.
def is_spam(string, tollerance=3):
consecutive = 0
last_letter = ''
for letter in string:
if letter == last_letter:
consecutive += 1
if consecutive >= tollerance:
return True
last_letter = letter
return False
``` A better version here
how do i add a mobile status using discord.py?
e_count = 0
for "e" in message.content:
e_list += 1
spam = False
if e_count >= 10:
spam = True
I think this should work.
If you're counting how many e's are in the message.
This is not a great idea.
so it is not possible to add mobile status to it?
It's done using routes as Discord wouldn't open this feature in its API.
thats not what is needed. he wants to count consecutive characters not total
oh, why not?
Ah. Then one second.
You should keep track of how many equal consecutive characters there are
as i said, it requires monkeypatching
ahh okay
iirc its a bug when you send the identify payload
Yeah.
!d collections.Counter
class collections.Counter([iterable-or-mapping])```
A [`Counter`](https://docs.python.org/3.10/library/collections.html#collections.Counter "collections.Counter") is a [`dict`](https://docs.python.org/3.10/library/stdtypes.html#dict "dict") subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The [`Counter`](https://docs.python.org/3.10/library/collections.html#collections.Counter "collections.Counter") class is similar to bags or multisets in other languages.
Elements are counted from an *iterable* or initialized from another *mapping* (or counter):
```py
>>> c = Counter() # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping
>>> c = Counter(cats=4, dogs=8) # a new counter from keyword args
!e
import collections
text = "Hello world"
frequencies = collections.Counter(text)
repeated = {}
for key, value in frequencies.items():
if value > 1:
repeated[key] = value
print(repeated)
@dapper cobalt :white_check_mark: Your eval job has completed with return code 0.
{'l': 3, 'o': 2}
Yeah, I know.
I was copying an example.
oh kite
@outer ridge
Does he want to detect how many times a character is repeated next to itself?
So like "eeeeeeee" = spam
"hey ey eyo" != spam
this is the original issue
One moment.
ok
big question
whats a decorator? i feel like this is an important term that i need to know
but nobody's explain that to me yet
import collections
@client.event
async def on_message(message):
messages = []
async for message in ctx.channel.history(limit=3)
messages.append(message.content)
frequencies = collections.Counter(messages)
for key, value in frequencies.items():
if value >= 3:
spam = True
I believe this works. This checks if the last 3 messages sent are the same.
Imo a good way to detect duplicated messages is via difflib.get_close_matches, the cutoff can be set to what you want and harder to bypass if you only add a few extra characters
Just check if that returns None else count it as spam
@this_is_a_decorator
?
async def on_ready():
await client.change_presence(activity=discord.Streaming(name="coolin with slums", url="https://twitch.tv/fraudpays"))
print("daddy is online.")``` should i keep my status cmd in `@client.event`?
or is it not appropiate to
like @bot.event would be a decorator?
Yes.
k
.
I think this could help more. https://www.datacamp.com/community/tutorials/decorators-python
@fallow mauve
ok
You can, but not very recommended. Instead, you could use wait_until_ready.
!d discord.ext.commands.Bot.wait_until_ready
await wait_until_ready()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits until the clientâs internal cache is all ready.
yu
ty*
where will i have to add this in the code?
What
Why would you put that there just pass activity when constructing the bot
What would wait_until_ready even do here to help??
wait until the bot is ready? ig idk xd
i see the point of it but idk
How would that help
on_ready is litteraly fired when the cache is ready
WHICH is the exact same thing wait_until_ready does
i have no idea
infact wait_until_ready waits for on_ready in a sense
Anyhow this wouldn't fix the problem of it firing multiple times
which is why you pass the activity kwarg when constructing the bot
how will i fix the problem of it firing multiple times
by removing it from on_ready and passing activity kwarg to the bots constructor
alright ty
hello
@client.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, reason=None):
await member.ban(reason=reason)
await ctx.send(f'User {member} has been kick')
``` gives me an error: member was not found
Ill just give you mine
@ client.command(pass_context=True) @ commands.has_permissions(administrator=True) async def ban(ctx, member: discord.Member, *, reason=None): await ctx.send(f'Nuked { member.mention}')
Should work just fine
whats wrong with this? my alt acc does not have kick members perm yet can use the command
nice edit lol
first ctx.send
I never seen anything like this....
I'm sure @hasty iron got an answer. đ
Sorry blanket, not sorry blanket.
like this @fallow mauve
has_guild_permissions is a decorator for commands
just use what you need
@commands.has_permissions(kick_members=True)
command decorators dont work on events
or just @ commands.has_permissions(administrator=True)
youâll have to check if on your own inside the function
its fine
đ
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Also why administrator permissions to ban?
anything decorated by Bot.command or commands.command
that doesnt ban the person...
How do i make it add makes you add your own colour?
@client.command()
async def make_embed(ctx):
def check(message):
return message.author == ctx.author and message.channel == ctx.channel
await ctx.send('Waiting for a title')
title = await client.wait_for('message', check=check)
await ctx.send('Waiting for a description')
desc = await client.wait_for('message', check=check)
await ctx.send('Waiting for a colour')
desc = await client.wait_for('colour', check=check)
embed = discord.Embed(title=title.content, description=desc.content, color=colour.content)
await ctx.send(embed=embed)```
!d discord.ext.commands.ColourConverter
class discord.ext.commands.ColourConverter(*args, **kwargs)```
Converts to a [`Colour`](https://discordpy.readthedocs.io/en/master/api.html#discord.Colour "discord.Colour").
Changed in version 1.5: Add an alias named ColorConverter
The following formats are accepted...
how do i add a specific role to a channel? i have default user and role, but idk how to set a specific one. ```py
await ticket_channel.set_permissions(ctx.guild.default_role, send_messages=False, read_messages=False)
await ticket_channel.set_permissions(ctx.author, send_messages=True, read_messages=True, read_message_history=True, embed_links=True, attach_files=True, add_reactions=True)
how to make music command?
lol
Get the role and do as you did with ctx.author. Also, you could just set the overwrites like this:
overrides = {
ctx.guild.default_role: discord.PermissionOverwrite(send_messages=False, read_messages=False)
ctx.author: discord.PermissionOverwrite(send_messages=True, read_messages=True)
}
ticket_channel = await ctx.guild.create_text_channel(name="name", overwrites=overrides)
um
how i do it exactly?
No module named 'discord_buttons_plugin' someone know why?
from discord_buttons_plugin import *
await commands.ColorConverter.convert(ctx, "#fffff")
Have you installed the module?
In what sense?
Huh?
?
This won't work just like all other converters you need to create an instance first then use the convert method
Could you but it in like these formats please?
await ctx.send('Waiting for a description')
desc = await client.wait_for('message', check=check)```
Right. My bad.
converter = commands.ColorConverter()
converter.convert(ctx, string)
@dapper cobalt
Is it possible to add an additional dialogue after a second message of the user when the first message sent has been triggered?
For instance :
I say the keyword "hello"
If it's "hello" it will respond with "what do you need"
However, if I say "I need popsicle", the bot will respond with something too
if not, it will return
If "hello" is not here it will return as well
Basically a dialogue. More or less.
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
thank you
can i put days in tasks.loop?
A random question, would it be smart to store your bot's data into a json file, and have the bot upload it into some discord channel?
Basically using a channel to store data instead of a database or anything else. Even though a database would be way better for storing data, but a json file for storing the bots config, such as prefix and whatever else, should be good enough, right?
nvm you cant
You could probably use exponents
yea nvm im just gonna use hours
Alr
also, can someone explain me what the reconnect parameter does in tasks.loop?
if the bot disconnects will it start from the time it left or will it start a whole new loop?
It continues running the loop after one iteration has errored, if reconnect isn't set to true it just raises the error
oh, so if an error has occurred it does not stop, it keeps going?
Yep if reconnect is set to true it basically suppresses the error and continues running
ah ok thanks
@client.event
async def on_command(command):
@client.has_permissions(manage_roles=True)
async def create_role(ctx, *, name):
guild = ctx.guild
await guild.create_role(name=name)
await ctx.send(f'Role `{name}` has been created')
whats the command for this
like what do i type in my server to actually use it
this is not a command
the decorator goes ontop of the command
wait a minute ,its a event
itâs not a command; like i said
also is on_command even a decorator in discord.ext.commands?
i just get this ```line 43, in <module>
@client.command
AttributeError: 'Client' object has no attribute 'command'
ohhh
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
hey, im trying to do change prefix between servers but i got an error everytime. someone knows?
u talk to me?
its ok
so do i just slap it under ```client = discord.Client()
You should try and use the bot extention over attempting to use the client directly. Heres a full example of it you can take a look at: https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py
remove that
im gonna do this on a different bot
how do i start a for loop inside a if statement
someone?
ping the snow dude for help or the sofi yes spooky person they seem to know
@pliant gulch sorry for ping, but what do you think this does?
from discord.ext import tasks
from datetime import datetime
import asyncio
@tasks.loop(seconds=30)
async def test():
channel = bot.get_channel(856373686809788430)
await channel.send("test")
startdate = datetime(2021,9,27,22,28,00)
await discord.utils.sleep_until(startdate,test.start())
Starts the task at that time
Then afterwards it runs in 30 second intervals
ye but it still sends the hi before it
idk why
Is the time you set past the current time?
Probably some weird time zone stuff then
ooooo
As it always run if the set time is past current time
So
I've 2 bots, copied the command from one bot, pasted the code in the other-
The command in the first bot is working, not in the new one. What the fuck? The command only works when its used with the bot
Its a userinfo command, it displays userinfo lmao
So when I do !userinfo <bot_id> it works, when I use the command with another user it doesnt
off still does it
set tzinfo as timezone.utc
Not sure then all I know is that it doesn't sleep if the time set is already passed
hm ok thanks
Concerning about wait_for(event, *, check=None, timeout=None)
I was wondering if there's a way to break this waiting if someone sends a message that doesn't include the keyword required.
Like an If/Else
any idea why this could be happening? i can share my code
so weird, and in this other bot it works with every user
yeah
!d discord.Embed.set_footer
set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
icon_url
icon_url kwarg
^^^
why does it say set_footer isnt defined
code
@client.command()
async def help(ctx):
embedVar = discord.Embed(description='''**Commands Help!**\n\n**â€Prefix(.)**\n**â€
All the commands within this bot include**\n\nâ€.help\nâ€.Ping\nâ€.locklist\n
â€.staffapp\nâ€.clear\nâ€.8ball\nâ€.addrole\nâ€.kick\nâ€.ban ''', color=0x2AD7B6)
msg1 = await ctx.send(embed=embedVar)
set_footer(text=current_time, icon_url='UDMLogo.png')
your pfp
ill move ctx.send embed to after I set footer
set_footer isn't defined by itself, its a method of Embed objects
hmm
you need to call it on embedVar
yes my cat
embedVar.set_footer
Also
Nevermind on that, you just need to make sure there's no check. As long as it's not broken it's good.
Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:
# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")
# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
file = discord.File(f)
When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.
discord.Embed instances have a set_image method which can be used to set an attachment as an image:
embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png") # Filename here must be exactly same as attachment filename.
After this, you can send an embed with an attachment to Discord:
await channel.send(file=file, embed=embed)
This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.
its his var name đ
@proven elm send the image through discord in a random server. Click on open original then copy the url. Then paste the URL into the footer
Oh didn't see that, thought you were a camelCaser for a second
i got it, i used before_loop and it worked
hi i need help i'm trying to make a discord bot and this syntax keeps popping up and i dont know why
@client.command()
async def help(ctx):
embedVar = discord.Embed(description='''**Commands Help!**\n\n**â€Prefix(.)**\n**
â€All the commands within this bot include**\n\nâ€.help\nâ€.Ping\nâ€.locklist\n
â€.staffapp\nâ€.clear\nâ€.8ball\nâ€.addrole\nâ€.kick\nâ€.ban ''', color=0x2AD7B6)
embedVar.set_footer
file = discord.File("./UDMLogo.png", filename="UDMLogo.png")
f = discord.File("./UDMLogo.png", filename="UDMLogo.png")
embedVar.set_image(url="attachment://image.png")
await ctx.send(file=f, embed=embedVar)
Why is it not sending the image in the embed
oh
any idea why it wont send the image inside the embed?
print has to be in one line
thank you
np
hmm
@client.command()
async def help(ctx):
embedVar = discord.Embed(description='''**Commands Help!**\n\n**â€Prefix(.)**\n**
â€All the commands within this bot include**\n\nâ€.help\nâ€.Ping\nâ€.locklist\n
â€.staffapp\nâ€.clear\nâ€.8ball\nâ€.addrole\nâ€.kick\nâ€.ban ''', color=0x2AD7B6)
embedVar.setfooter('UDM Staff Bot âą', current_time)
embedVar.set_image(url='UDMLogo.png')
await ctx.send(embed=embedVar)
Why is it not sending it to discord
I presume I need to use something other then ctx.send but idk what
pls what do i do
do this
print('''we have logged in as {0.user}
'''.format (client))
or what
got to line 9 and move it up to the 8th
just put it on one line or use ''' three of these symbols to multi line it
?
i think its the set_image
in the set_image it has to be path/to/image/image.png
ohhh ok
How do I get the embed info like the title or description from a message, is it py for embed in message.embeds: embed = discord.Embed(color = embed[0].colour, description = embed[0].description)
I know it
@stark hearth
now there's anoteher syntax
how do I fix it?
alright thank you
whats the error
idk
oh it has to be like attachment://image.png
@proven elm
like this?
embedVar.set_image(url='attachment://UDMLogo.png')
hey how can I make a command usable in a specific channel ???
yeah
still not working
use an if statement to check if the command they are running is being used in the correct channel or not
hello guys, i am a new . can anyone help me. the question is ( how i need learn python for cyber security and pentesting? any books? web ?
Hello
@client.command()
async def rank(ctx,crypto):
await ctx.send(get_crypto_rank(crypto))
this is the command can you show me how to it please?
hi
i think i did something rightish now there is yet another syntax
@dusk pumice hello
clint?
lol
client.run should come out of the asyn code
already done it
ok~~
import discord
import os
client = discord.Client()
@client.event
async def on_ready():
print ('''we have logged in as {0.user} '''.format (client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith ('$fallout'):
await message.channel.send('beginning fallout procedures adios amigos')
client.run(os.environ('MATTHEW PASSWORD'))\
done
I think you should learn the python basics first ngl you didn't know how to print two lines or how to use ==
try this import the image to discord and copy the link to url @proven elm
or any image link service
ight
import discord
import os
client = discord.Client()
@client.event
async def on_ready():
print ('''we have logged in as {0.user} '''.format (client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith ('$fallout'):
await message.channel.send('beginning fallout procedures adios amigos')
client.run(os.environ('MATTHEW PASSWORD'))```
https://imgbb.com/ this site is popular for making image urls
Free image hosting and sharing service, upload pictures, photo host. Offers integration solutions for uploading images to forums.
this might work
and also u defined the client.event decorator inside another client.event decorator thats not right @jovial cypress
@proven elm sorry for delay because im doing my essay at the same time
no worries bro
embedVar.set_footer('UDM Staff Bot âą', current_time)
embedVar.set_image(url='https://ibb.co/JFvtMWN')
await ctx.send(embed=embedVar)
still not working
whats ur error?
none, no error at all but when I add the embedVar.setfooter and set_image it just doesnt send anything, if I remove those two lines then it will send the text
did u defined embedVar object?
@client.command()
async def help(ctx):
embedVar = discord.Embed(description='''**Commands Help!**\n\n**â€Prefix(.)**\n**
â€All the commands within this bot include**\n\nâ€.help\nâ€.Ping\nâ€.locklist
â€.staffapp\nâ€.clear\nâ€.8ball\nâ€.addrole\nâ€.kick\nâ€.ban ''', color=0x2AD7B6)
embedVar.set_footer('UDM Staff Bot âą', current_time)
embedVar.set_image(url='https://ibb.co/JFvtMWN')
await ctx.send(embed=embedVar)
full code
Nope
but bot send embed send but img not coming?
wait whta
but if I remove those 2 lines then it sends
whats ur bot prefix?
which two?
embedVar.set_footer('UDM Staff Bot âą', current_time)
embedVar.set_image(url='https://ibb.co/JFvtMWN')
Guys I need some help. Anyone have any alternate suggestions for the on_reaction_add event, the issue with this reaction event is it only activates the function to messages sent AFTER the bot was turned on not before.
nah don't have that
did you import tasks?
nah why?
I was recommended imgbb
my bad my bad
try anyother google img
oh thank you
huh try this
yeah
for current_time it uses tasks so do from discord.ext import commands, tasks
actually I did import tasks already
I use it to loop through activity statuses
ahh ok
also still doesnt send image
code again?
maybe send code again
@client.command()
async def help(ctx):
embedVar = discord.Embed(description='''**Commands Help!**\n\n**â€Prefix(.)**\n**
â€All the commands within this bot include**\n\nâ€.help\nâ€.Ping\nâ€.locklist
â€.staffapp\nâ€.clear\nâ€.8ball\nâ€.addrole\nâ€.kick\nâ€.ban ''', color=0x2AD7B6)
embedVar.set_footer('UDM Staff Bot âą', current_time)
embedVar.set_image(url='https://i.ibb.co/gFS9BbG/UDMLogo.png')
await channel.send(embed=embedVar)
await ctx.send(embed=embedVar)
did you save?
i finished my calculator buttons command and i just tried it but whenver i put a symbol or another number it gives me this, idk whats happening
i am currently learning buttons, so i cannot help you sorry
did you save the code?
ok
wait why do you have await channel.send(embed=embedVar) and await ctx.send(embed=embedVar)
just do await ctx.send(embed=embedVar)
tried both to see if it would work
still doesnt work
that's gonna give him an error
mate i think u might remove that current_time in set_footer
are u good?
yeah
Remove the channel.send
yea
I did
ctx.send is enough
still doesnt send an embed image
thats what i said though
his problem is in embed image not coming
again, not defined so it would give an error, and ctx.send literallt does the exact same thing
also i am sleep deprived over this essay
If you want current time I would suggest adding a timestamp with ctx.message.created_at in the discord.Embed object
he defined ctx
ahh okay thank you
So you would add timestamp=ctx.message.created_at
yeah ik i just asked him why you have both
@slate swan
the reply pings me u dont have to do it twice.
done that didn't change anything
my bad
but anyways
whats the issue here
still doesnt send embed image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
errors?
@client.command()
async def help(ctx):
embedVar = discord.Embed(description='''**Commands Help!**\n\n**â€Prefix(.)**\n**
â€All the commands within this bot include**\n\nâ€.help\nâ€.Ping\nâ€.locklist
â€.staffapp\nâ€.clear\nâ€.8ball\nâ€.addrole\nâ€.kick\nâ€.ban ''', color=0x2AD7B6)
embedVar.set_footer('UDM Staff Bot âą')
embedVar.set_image(url='https://i.ibb.co/gFS9BbG/UDMLogo.png')
await ctx.send(embed=embedVar)
this code isnt sending embed image
does it send the embed without the image or the whole embed isnt getting sent
nothing is being sent
set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
takes only kwargs
thats for icon url bruh
yeah and text is useless
so how do I solve my issue?
But set_image takes https: images???
set_footer takes only kwargs and their passing in it as positional
text= ?
whatever you want
yea try
slightly
then you should know how it works
keyword arguments
sends nothing, nothing happens
Embed.set_footer takes only kwargs
they are keyword arguments
kwargs is an abbreviation for keyword arguments
ik... i just said that?
Hello guys I want to learn python to code some discord bots, how much knowledge of python would you guys say is needed in order to start with discord library? Maybe the basic level of python? Or go in depth with python and then move on?
send your updated code
How much Python do I need to know?
discord.py is ultimately a complicated Python library for beginners. There are many concepts in there that can trip a beginner up and could be confusing. The design of the library is to be easy to use -- however the target audience for the library is not complete beginners of Python.
With that being said, beginners tend to use this library quite liberally anyway and while I appreciate the endeavour and tenacity it should be noted that asking for help here does take up the valuable time of volunteers. As a result certain knowledge is required before you can actively participate in the help channels:
- The difference between instances and class attributes.
- e.g.
guild.namevsdiscord.Guild.nameor any variation of these.
- e.g.
- How to use data structures in the language.
dict/tuple/list/str/...
- How to solve
NameErrororSyntaxErrorexceptions. - How to read and understand tracebacks.
This list is not exhaustive
If these concepts are confusing -- please feel free to complete a smaller and simpler project first before diving into the complexities that is asynchronous programming in Python. The Python help channel (#738572311107469354) or the Python server (https://discord.gg/python) could also be a place to go for basic Python help.
@client.command()
async def help(ctx):
embedVar = discord.Embed(description='''**Commands Help!**\n\n**â€Prefix(.)**\n**
â€All the commands within this bot include**\n\nâ€.help\nâ€.Ping\nâ€.locklist
â€.staffapp\nâ€.clear\nâ€.8ball\nâ€.addrole\nâ€.kick\nâ€.ban ''', color=0x2AD7B6)
embedVar.set_footer(text='UDM Staff Bot âą')
embedVar.set_image(text='awdawd',url='https://i.ibb.co/gFS9BbG/UDMLogo.png')
await ctx.send(embed=embedVar)
functions, asyncio, api's, variables, etc
you dont need to know apis
i want to use the bot to interact with google sheets, isnt that an api?
he need to know api docs
?
well at least understand how to read it?
why?
do you know what an API is
ik
why are you passing in text to set_image
:kekw: i didnt notice
i think you mean, "how to read docs"
yes
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
even if I dont pass in text still doesnt work
they have an api, that's how its able to work within python to begin with
!paste send your full code
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.
like everything
except the token ofc B)
api is not a module its a webinterface which only servers GET,POST
that should be obvious
I JUST SAID...
BRO READ THE WHOEL THING BEFORE U SAY SUM
ok
you would have to be a menace to send your token >:)
api doesnât necessarily mean an http webserver
it can be anything
what is the optimal way to learn python? i was looking for online courses in datacamp, udemy, etc. I dont know if theres a better option to learn
thats the most splified i can give u
inside the on_command_error add
else:
raise error
Honestly... i just used youtube.
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Once I learned everything I should be learning, like statements, variables, classes, other instances, error handling, traceback
@hasty iron
I just kinda came into discord.py and see what's good using the API reference
url=
ill remove it
its already told
text is not in set_image
remove it
why are you still passing it
yea
FINALLY IT WORKS!!
what are u passing set_image...
boom
now how do I place the image in the footer instead
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
đ
url is the only kwargs
!d discord.Embed.set_footer
set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
may i ask what youtube videos you used to learn? i know theres a loot of videos
icon_url
icon_url
again, its a kwarg
I think he gets it now lol
yt vids how many hours u gonna waste?
read docs for kwargs @proven elm
any, i lack a life right now đ
most of them are old i would recommend reading the updated docs
they are talking about python not dpy
oh lmao my bad
use free interactive services like freecodecamp
videos for python are mostly fine, but you should do your own research, like reading python docs
they have videos and interactive practices for you
^^^
image looks kinda cut off?
lol
lmao
thats how it comes
blame discord
ight nw thank you guys
ok thank you guys
why?
thats hows its built
lol then why blaming
u cant do nun about that
yeah
it was meant as a joke but ok
hmm
u cant edit image sizes in set_footer
no
no kwags support it
maybe edit a pic to that pixel and use it
there are no kwargs in it that lets u do this*
the Travel right?
yeah
countries = random.choice(Travel)
wrap the expression in {} like in other places in the string
The {} in an f-string makes it evaluate it
rather than show it literally
at last saw an admin responding here
ty
Is this the correct way to get my bot to copy and send each embed in a msg starting from the second one (sending the first one in a different msg)py await ctx.reply(content = plain, embed = embed[0].copy(), components = [action_row]) if len(message.embeds) > 0: for embed in message.embeds[1:]: await ctx.reply(embed = embed.copy())
Why do the all need to be in separate messages?
Either way, you shouldn't need to use copy
Maybe you didn't make it edit the message? Or it's a discord problem
Hello is it better to use events or commands?
well, commands are cleaner imo, there are many events, both are useful
utilize both, but when making commands please make them using the command decorators from discord.ext, not with an on_message event.
if I wanted my commands to run in one channel can I make just one if statement or I have to write the if statement for every command?
you could write a function, or make your own decorator for it
you could use a check https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check , its way cleaner
what do you mean by write a function
um, how do you hide a cog? Is hidden a thing in Cog?
this command isnt working, any idea why?
looks fine to me, do you have an on_message event?
any errors when you run the command?
yeah
yeah, but that hides the commands
you have an on_message event..
mhm
how about the cog then?
does that mess it up?
you need to process commands probably
and hidden = True raises TypeError: __init_subclass__() takes no keyword arguments
dont know about that
await bot.process_commands(message)
command_attrs=dict(hidden=True)
!d discord.ext.commands.CogMeta
class discord.ext.commands.CogMeta(*args, **kwargs)```
A metaclass for defining a cog.
Note that you should probably not use this directly. It is exposed purely for documentation purposes along with making custom metaclasses to intermix with other metaclasses such as the [`abc.ABCMeta`](https://docs.python.org/3/library/abc.html#abc.ABCMeta "(in Python v3.9)") metaclass.
For example, to create an abstract cog mixin class, the following would be done...
where would that go in the code?
Try seeing that. It has the args
at the end of the on_message handler
top or bottom of your on_message event
It only takes command_attrs, name and description
at the end of on_message event
make sure its not under any if conditions either
Or just change the deco. It's an easier way
to a listener?
@bot.listen() instead of @bot.event
You can set your own hidden attribute though @visual island
yeah i will
@patent lark
Ill probably make my own metaclass 
yeah
is this right?
deco?
decorator, that @something thing is called a decorator
Yea that ^^^
My bad
ok, thx for finally explaining that to me
at end
nobody had done that yet
command "say" still not found
he did
Hmm
I know why
what
The command name is <say (ctx
Cz that's what u specified in the deco
Try running with this name
just put say in there, or just leave it empty cuz the func name is already say
try removing the thing inside the deco
oh lol
nvm
...not that one, the one at your say command
this?
remove the <, just put say in there, or just leave it empty cuz the func name is already say , d.py will do the command processing, you don't need to add the prefix in the command name
yeah like i said, a listener
works, thx so much
whats the difference between .listen() and .event?
y'all are really helping me a lot, ive learned so much about python in the last few days
when you listen for an event, you can specify the event you listen to, @bot.listen("function_name") and then you could define the function as anything you want, i dont know too much about the benefits, but i know that with on_message it removes your requirement to process commands, and its good when you want mutliple on_message events.
no problem
im making this bot to help in the discord server for my friend's mc SMP and im trying to learn python as i make it, so thx for helping me with this, i rly appreciate it
đ
I wanna get a list of the guild names that my bot is connected to..
Here is my code: py @bot.event async def on_ready(): for guilds in bot.guilds: print(guilds.name)
But the code gives error: 'Guilds' is not iterable
Please help
never used guilds, sry
:(
*in code
No need to input the function name
just watch a tutorial on youtube like how to add options to slash commands in discordpy examle /add num1 num2
if you'd like to change the name of the function you define then yeah, like if you want two on_message events
Yea
I actually write my discord bot code in replit, although I was wondering if you could play an mp3 file from the bot in VC, by playing the mp3 file that was locally given on replit.
I know.
you can
dunno how tho
That's how music bots kinda work IDK how it can be done but it can be
thats what I just said
đ
I know you can do something like this, although I'm not sure how am I supposed to implement it on a command. Most of the tutorials are referring to youtube_dl, but we can't do that anymore.
can we mention someone in discord embed title?
Nope
The title is fully MD'd
ok
Can anyonr help me
i tried making a make embed command but how do i added image?
@client.command()
async def make_embed(ctx):
def check(message):
return message.author == ctx.author and message.channel == ctx.channel
await ctx.send('Waiting for a title')
title = await client.wait_for('message', check=check)
await ctx.send('Waiting for a description')
desc = await client.wait_for('message', check=check)
await ctx.send('Waiting for a Image')
image = await client.wait_for('link', check=check)
embed = discord.Embed(title=title.content, description=desc.content,image=image.content,color=0x2f3136)
await ctx.send(embed=embed)```
It's guild.name
any mistake?
Color
guild.name
discord.Color?
After success put a comma and change name of colour to color
Yeah its spellling is american
ohh i worked with embed a lot of time ago so i almost forgot about it đ
!d discord.Colour
class discord.Colour(value)```
Represents a Discord role colour. This class is similar to a (red, green, blue) [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)").
There is an alias for this called Color...
Oh lol
you are missing a comma after success'
title="whatever", colour=..
yeah got it
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
yes
you can use either
How i do it exactly
embed.set_image(url="your image url")
you can use both color and colour
Its not like one of those its a custom embed command
Code is here
this @lyric moat
Ik that but its a custom embed it makes the embed for you in chat
after getting the message object from py image = await client.wait_for('link', check=check), you can use```py
embed.set_image(url= image.content)
also , if the user enters a wrong url , whole embed fails so make sure to use try and except
error
read the docs of set_image
set_image is a function
its not a parameter
is a function
^
embed = discord.Embed(title = title.content, description = desc.content, color = 0x2f3136)
embed.set_image(url = image.content)
if this isnt the proper place to message this, i am sorry
!rule 9
Sorry
- Missing comma after title.
- Discord.py allows both
ColourandColor.
You could do ```py
embed=discord.Embed(title=title.content, description=description.content, color=0x2f3136).set_image(url=image.content)
How do I make the image works?
does not work
isn't this how we import cogs?
is your folder named commands right?
also it has to be commands. in load extension
what's ur folders name?
^^^
yes it is
It should commands.{filename.âŠ
its client.load_extension(f'commands.{filename[:-3]}')
is it possible for discord bots to ignore mentions from replies?
what is this? it can't recognize
mention_author=False
oh alright thanks
@stark hearth
Did u made a cog command?
yes
it is in commands folder
and i wanna import it in main.py
It's replit?
yes
Aah idk
i think it works in the same way as in vscode or any other ide
I didn't got any error like this
For this code u should make command called load and unload so that u can load cogs
it a error in the cog
did u setup cog
yes
Send cog code here
ok
"Extension 'commands.warn raised an error:"
import discord
from discord.ext import commands
import pymongo
from pymongo import MongoClient
cluster = MongoClient('mongodb url')
database = cluster['discord']
collection = database['warn-database']
class Warn(commands.Cog):
def __init__(self, client):
self.client = client
# command
@commands.command()
@commands.has_permissions(manage_channels = True)
async def warn(self, ctx, user: discord.Member = None, *, reason=None):
id = user.id
if collection.count_documents({"memberid": id}) == 0:
collection.insert_one({"memberid":id, "warns": 0})
if reason == None:
return await ctx.send('Please mention a valid reason!')
elif user == None:
return await ctx.send('Please mention a member to warn!')
warn_count = collection.find_one({'memberid':id})
count = warn_count['warns']
new_count = count + 1
collection.update_one({'memberid':id}, {'$set':{'warns':new_count}})
warn_embed = discord.Embed(
title = f'Successfully warned {user.name}',
colour = discord.Colour.red()
)
warn_embed.add_field(name = 'Reason', value = reason, inline = False)
warn_embed.add_field(name = 'Warned by', value = ctx.author.name, inline = False)
warn_embed.add_field(name = 'Total warnings', value = new_count, inline = False)
await ctx.send(embed = warn_embed)
def setup(client):
client.add_cog(Warn(client))
the cog
your mongodb url is formatted wrong, idk pymongo tho
u mean invalid url?
yes, from looking at the error
i just copied and pasted the url from mongodb and changed the <password> with my password
without space
i think it is correct
it is correct
i chacked
i want it to ignore reply mentions
uh no
make it
thats whi it says
also
if u want the bot to reply but it will not tag him
thts not what im saying, ive my bot reply to mentions with its syntax and help command, and i want it to ignore mentions that are from replies
idk really but ig it is await message.reply(mention_author = False)
yes
im not talking about that
idk much about mentions sorry
you know how when u mention bots, they reply with what their prefix is
yes
ok
is that possible?
so i think it is
is there message.type? idk
wait
lemme see docs
this can help
pls help
for what member updates?
Hello i had a small doubt
I want my bot to send the message in one line itself
but it says the message.send() takes only one argument
can you send your code?
sure
if message.content=="/hello":
await message.channel.send("Hello there!")
await message.channel.send(a)```
I want to send it in one message
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
Does this help?
Also think on making commands instead of waiting for a message
As rather soon you won't be able to do it, message intents will be there.
Thanks a lot it worked
Yeah thanks will do
yes
well, before and after are discord.Member objects
Also everyone here uses pycord right
nop
i dont trust any forks of dpy as of rn
thanks
I use pycord-fork-discord-fork-disnake-components.py
Nice
Well you have to sooner or later
discord.py forks popularity: đŠŸ
discord.py forks api coverage: đ©
also i dont think bots will be a thing anymore in 2023
y