#discord-bots
1 messages · Page 569 of 1
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.
it is enabled, and it's also not empty
no
or your bot is broken
nothing can help you
intents = Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)
maybe it's the d.py versions? i'm using master
thanks
me2
and me2 using history
(if you mean master is 2.0)
@slate swan what happened?
Ignoring exception in command очистить:
Traceback (most recent call last):
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\converter.py", line 1085, in _actual_conversion
return converter(argument)
ValueError: invalid literal for int() with base 10: 'fgjgh'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 995, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 887, in invoke
await self.prepare(ctx)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 821, in prepare
await self._parse_arguments(ctx)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 727, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 579, in transform
return await run_converters(ctx, converter, argument, param) # type: ignore
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\converter.py", line 1182, in run_converters
return await _actual_conversion(ctx, converter, argument, param)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\converter.py", line 1094, in _actual_conversion
raise BadArgument(f'Converting to "{name}" failed for parameter "{param.name}".') from exc
nextcord.ext.commands.errors.BadArgument: Converting to "int" failed for parameter "amount".
How to check if a person wrote some text to him or wrote something
Code
import nextcord as discord
from nextcord.ext import commands
class Utilities(commands.Cog):
def __init__(self, bot):
self.bot = bot
#----------очистить----------#
@commands.command(name= "очистить")
async def clear(self, ctx, amount:int = 0):
if amount == 0 or amount >= 100:
embed = discord.Embed (
title = 'Команда `s~очистить`',
description = 'Команда `s~очистить` очистить какое-то количество сообщений \n в данном канале. Не забудь что я могу очистить 100 сообщений за раз, а также \n очень древние сообщения я не смогу удалить.',
colour = 0x694c5f
)
embed.add_field(name= "Использование:", value= "> `s~очистить` `(Количество)`", inline= False)
embed.add_field(name= "Параметры:", value= ">>> <> - Необязательный параметр \n () - Обязательный параметр", inline= False)
embed.add_field(name= "Пример:", value= ">>> `s~очистить` `100` \n ⮩ Очистит 100 сообщений", inline= False)
await ctx.reply(embed = embed)
else:
await ctx.channel.purge(limit= amount)
embed = discord.Embed (
description = f':white_check_mark: Удаленно `{amount}` сообщений',
colour = 0x694c5f
)
await ctx.send(embed = embed,)
#---------------------------#
def setup(bot):
bot.add_cog(Utilities(bot))
print("Ког Utilities роботает")
```]
yes
error handlers
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
and which one exactly
@clear.error
Thanks
there is no need for him to output something if a person wrote letters and not numbers
k then typing.Optional for you
Let's go to the bos
bos?
ls
i dont understand you sry..
I can't get the message.content of the messages using channel.history()
Weird. Can I see the code u using?
if utils.get(ctx.guild.text_channels, name="mod-logs"):
print("before")
channel = utils.get(ctx.guild.text_channels, name="mod-logs")
print(type(channel))
for message in channel.history:
print(type(message.content))
print(message.content)
else:
print("not working")
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
ahh I see lemme try that
async for msg in channel.history()....
message.content returns a type of str
Yea
but it doesn't print anything when i print it
Code
if utils.get(ctx.guild.text_channels, name="mod-logs"):
print("before")
channel = utils.get(ctx.guild.text_channels, name="mod-logs")
print(type(channel))
async for message in channel.history(limit=None):
print(type(message.content))
print(message.content)
else:
print("not working")
else
Hmm
assuming the amount of every message in the channel
but why wont it print the content?
I mean guys I'm creating a translation command for my bot, here the code:
async def translate (ctx, lang_to, * args):
lang_to = lang_to.lower ()
if lang_to not in googletrans.LANGUAGES and lang_to not in googletrans.LANGCODES:
raise commands.BadArgument ("This language does not exist.")
text = '' .join (args)
translator = googletrans.Translator ()
text_translated = translator.translate (text, dest = lang_to) .text
await ctx.send (text_translated)``
My problem:
raise TypeError ("Aliases of a command must be a list or a tuple of strings.")
TypeError: Aliases of a command must be a list or a tuple of strings.
(I tried to do what it said, but it gives the same error.)
876189455592062978
before
<class 'discord.channel.TextChannel'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
See, it's printing a new line, which means either the message content is empty, or u don't have message intent
Wait, enable the Message intent from discord dev portal
Haha
...........................................
i said it to him
he: it is enabled!
hate my life
Nah irsa new breaking change
U gotta enable it from Discord Dev portal
ThT shows the message intent problem tbh
wdym
if utils.get(ctx.guild.text_channels, name="mod-logs"):
channel = utils.get(ctx.guild.text_channels, name="mod-logs")
async for message in channel.history(limit=None):
print(message.content)
else:
print("not working")
this is the code, this should work right
Yups it should
it prints empty lines even after i enabled this thing
try using another library since discord.py doesn't work anymore, ig....?
wdym
It's stopped being maintained lol
lol what
Yea
but why does the code work for u and not me
Danny doesn't update it anymore
Never said it works for me... Also I use disnake, not dpy
danny not the daddy anymore.
Lmao
doesn't update and doesn't maintaining are different things
im using dpy and all is working
and not goind to switch cus it is easier to update it by myself
I mean, Danny isn't updating it anymore bro. U don't have context commands in those, nor slash commands and stuff
@bot.command()
async def info(ctx, member:discord.Member=None):
if member == None:
member = ctx.author
embed=discord.Embed(title="Cursex", description="**Identifitcation Card**", color = 0x5865f2)
embed.add_field(name="User's name:", value=f"{member.name}", inline=False)
embed.add_field(name="User's tag:", value=f"{member.discriminator}", inline=False)
embed.add_field(name="User's ID:", value=f"{member.id}", inline=False)
embed.add_field(name="Guild creation date:", value=f"{ctx.guild.created_at.strftime('%A, %B %d %Y @ %H:%M:%S %p')}", inline=False)
embed.add_field(name="Account creation date:", value=f"{member.created_at_strftime('%A, %B %d %Y @ %H:%M:%S %p')}", inline=False)
await ctx.send(embed=embed)
``` how do i make an "account creation date" thing
!d discord.Member.created_at
property created_at```
Equivalent to [`User.created_at`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.created_at "discord.User.created_at")
.
as in guild
confused
that's what i did? member
ok
oke
channel = guild.get_channel(828011225292079124)
NameError: name 'guild' is not defined
member.guild
@client.command()
@commands.has_role("Report Managers")
async def report_taken(ctx, message_id : discord.Message.id) :
how do i check if message_id author is the bot
fetch message, then check (message.author.bot)
like message = message_id
no
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
so how to do it
wait
@client.command()
@commands.has_role("Report Managers")
async def report_taken(ctx, message_id : discord.Message.id) :
the_message = await fetch_message(id)
like dat?
no
channel.fetch_message
idk from where to get channel
you can walk through all channels on the server
so
@client.command()
@commands.has_role("Report Managers")
async def report_taken(ctx, message_id : discord.Message.id) :
channel = client.get_channel(help_log)
the_message = await channel.fetch_message(id)
like dat?
yes
thank you
is it possible to get member.mention.id by on_message?
wtf is mention.id?
@client.command()
@commands.has_role("Report Managers")
async def report_taken(ctx, message_id : discord.Message.id) :
if message_id is None :
await ctx.send("Syntax : er!report_taken <message_id>")
else :
help_log = client.get_channel(help_log_channel)
report_message = await help_log.fetch_message(id)
if report_message.author is
i want to do if report_message.author is the bot how do i do it
T-T i am not sure, i am new
trying to
get roles of mentioned member on_message
if role xyz is there, send blah blah
if report_message.author.bot
but what if it is other bot like dyno
will it continue or stop
it will return True
yo what lib u guys use?
how do I store every time the bot is ready in a json/txt file?
dpy
i dont want that
so?
i want it is only the bot which is the mine bot
k then if report_message.author == client.user
you can still use it
thank ya
and what?
bad
i use other lib
any ideas?
whats a good lib for menus and buttons
menus
literally
thats what its called
wdym
discord_components
it has buttons
not sure about menus
discord.py 2.0 isnt bad
but it isn't maintained is it
and what?
u using pycord or nextcord?
ye
py or next
next
discord.py is now outdated?
i dont know about next
who knows how to find out how many messages the bot has deleted
new lib?
if snake is better then I'll switch to it
but discord_components work on pycord
how about snake?
i guess nextcord has its own command for buttons
disnake?
not heard its name
yo is there a new lib coming? what about discord.py? im not caught up with the stuff
discordpy is discontinued
discord.py is not maintained anymore
aw man
means no update
f
gotta migrate
what lib will replace dpy
nextcord is easy to switch to
oh i see
there are many forks
discord.py is NO LONGER UPDATED
You can still use discord.py, but with the next updates to the discord application, you will have to update this library yourself.
discord.py is working like this:
Request to Discord API (https://discord.com/developers/docs/interactions/application-commands)
Parse json output (https://docs.python.org/3/library/json.html)
(Requests: https://docs.python-requests.org/en/latest/)
Or you can use it's forks/unofficial parties
Such as pycord, nextcord and other...
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
pycord
damn
you don thave to change discord to nextcord
and here i was about refresh my discord.py skills
just uninstall discord then install py-cord no need to change the discord to nextcord
pycord has it own buttons and slash commands
hmmm nice
imma go google and search up stuff ;-;. This is getting confusng
but i dont know how to use em thats why i am using discord_components
so ut supports that too
niceee
what ut?
it
so what forks you guys prefer
pycord
i will switch to pycord rn
before switching
?
wait
i see, ill try all the forks. and choose whats better
dming
What makes pycord good?
maybe someone will pin this...
no need to customize your dpy code
just uninstall dpy and install pycord
Something like that is already pinned
wdym by "dpy code", i dont understand
oh you mean progress of the bot?
hi guys, I'm creating a translation command, here the code:
async def translate (ctx, lang_to, * args):
lang_to = lang_to.lower ()
if lang_to not in googletrans.LANGUAGES and lang_to not in googletrans.LANGCODES:
raise commands.BadArgument ("This language does not exist.")
text = '' .join (args)
translator = googletrans.Translator ()
text_translated = translator.translate (text, dest = lang_to) .text
await ctx.send (text_translated)
My mistake:
Command raised an exception: AttributeError: 'NoneType' object has no attribute 'group'
if you have a file called main.py which you created when discord.py is alive
and now as discord.py is dead you are migrating to pycord
now when you migrate to pycord you dont need to change the code
i see
Traceback (most recent call last):
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 606, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "O:\Suzuki\cogs\info.py", line 6, in <module>
class Info(commands.Cog):
File "O:\Suzuki\cogs\info.py", line 11, in Info
@bot.slash_command(name= "тян", guild_ids=[894452684072046652])
NameError: name 'bot' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "O:\Suzuki\bot.py", line 51, in <module>
bot.load_extension(f"cogs.{filename[:-3]}")
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.info' raised an error: NameError: name 'bot' is not defined
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x000001AFBA4DD780>
no problem for me tho
just pip uninstall discord and piiip install pycord and thats it
code
import random
import discord
from discord.ext import commands
import datetime as DT
from discord.ext.commands.errors import MemberNotFound
class Info(commands.Cog):
def __init__(self, bot):
self.bot = bot
#-----------тян-----------#
@bot.slash_command(name= "тян", guild_ids=[894452684072046652])
@commands.command(name= "тян")
async def than(self, ctx):
ping = round(self.bot.latency * 1000)
embed = discord.Embed(
title = 'Кто я?',
description = 'Я не большой бот, зовут меня **Сузуки**, надеюсь запомните.\nКак и все боты в моём стиле я `Тянка`. Ладно что-то я отвлеклась.\n\nЧто я могу? Ну в принципе как все боты я имею команды, для:\n`Модерации`, `Веселья`, `Получения информации`.\n\nНу на этом пока всё. Мой `Семпай` трудится и делает меня \n`Лучше`, `Красивее` и `Продвинутой`.',
colour = 0x694c5f
)
embed.add_field(name= 'Имя:', value= '>>> `Сузуки`')
embed.add_field(name= 'Создатель:', value= '>>> `Барабан4ик#3148`')
embed.add_field(name= 'Пинг:', value= f'>>> `{ping} мс`')
embed.set_footer(text= 'Барабан4ик © 2021 Все права у тянок', icon_url= 'https://cdn.discordapp.com/avatars/637685929611493422/32b105aa2097b6a3a84b2cda2f7b8e00.png?size=128')
await ctx.reply(embed = embed)
i dont have a discord bot being continued
while if you use nextcord you have to change all discord keywords to nextcord
piiip
pip*
error?
...
thats not how slash commands are made in a cog
also you dont use the same function for normal and slash cmds
and how
what library are you using?
I forgot to remove
py-cord
(it can be discord.py + discord_slash)
sorry for being dumb but this used to be normal and now i just came back to discord bots and this is getting confusing.
i better leave
thats what i asked , 'what library are you using'
is the pycord docs not updated or something?
i miss dpy, even though i just got to know that it is discontinued
mhm same , i shifted to a non-fork library now
oo, what is that library
hikari
!pypi hikari
suggested to use hikari-lightbulb with it , it makes it similar to commands.Bot
oo
interesting
I am trying to see if mentioned member has afk role
and send a msg then
but bot sends msg only if the author mentions himself
am i doing something wrong?
sorry i am new
async def on_message(self, message):
role = message.guild.get_role(self.afk)
if message.author != self.bot.user:
for member in message.guild.members:
if role in member.roles:
if member.mention in message.content.lower():
await message.channel.send(f"user is afk")
if member.id == message.author.id:
await member.remove_roles(role)
await message.channel.send(f"you are not afk anymore")
Thank you
hikari has a same syntax?
it doesnt
So like hikari has all the new features right?
well then I can't switch to it (or want to)
hikari is shit
ah i just want a good library
what's going on
discussion about discord libs
brrr never will use it
it doesn't :/
bro thats raw hikari , there are extnesions like lightbulb ( similar to ext.commands for dpy)
edpy, hikari is cringe
dies from cringe
@boreal ravine do u use a non-fork lib?
I use a fork
what is that fork
look at the image i sent with the message?
disnake
disnake is dope
latest version got autocomplete
sheesh
I think the owner of edpy hates py-cord for some reason
lmao
¯_(ツ)_/¯
thanks guys, ill try all the libraries and choose whats good
👍
if you guys can suggest me more id be happy
disnake is the best fork i would suggest
pog
alr
The image above it seems different
some guy was suggesting pycord ill try both
its like using discord.Client
where/how to install?
hello does anyone knows how to make a discord modmail
depends ¯_(ツ)_/¯
wydm depnds
on_message, if message channel is DM
^ depends
Well as a yes/no answer. Yes
same
k ill talk to u in dms
Can I help no
pip3 install -U git+https://github.com/Rapptz/discord-ext-menus?
yes u can
noice, thanks
class Bot(commands.Bot):
def __init__(self):
super().__init__(
command_prefix=commands.when_mentioned_or('l.'),
intents=discord.Intents.all()
)
async def on_ready(self):
print(f'{self.user} is ready!')
for file_name in os.listdir("./cogs"):
if file_name.endswith(".py"):
self.load_extension(f"cogs.{file_name[:-3]}")
client = Bot()
I think I have a problem with my help cog
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.help' raised an error: AttributeError: 'Bot' object has no attribute 'get_listeners'
Trying to DM me to get help... big no
hi guys, I'm creating a translation command, and I wish that when the bot translates the language it does it inside an embed, I just don't know how to do it.
here my code
async def translate (ctx, lang_to, * args):
lang_to = lang_to.lower ()
if lang_to not in googletrans.LANGUAGES and lang_to not in googletrans.LANGCODES:
raise commands.BadArgument ("This language does not exist.")
text = '' .join (args)
translator = googletrans.Translator ()
text_translated = translator.translate (text, dest = lang_to) .text
await ctx.send (text_translated)```
Whats with the spaces
the spaces are maked by discord, but my code don't have this spaces
@bot.event
async def on_reaction_add(reaction):
schannel = bot.get_channel(int(901834168357515284))
def count_reacts(msg):
count = 0
rlist = msg.reactions
for react in rlist:
count = count + 1
return int(count)
on reaction add takes 1 positional argument but 2 were given?
when did I give it two arguments 🗿
hi i made a bot that could fetch an image url from a show stats website which should update when the user changes their profile picture but when the link sends in discord the image is always the old image and not the updated one and idk how to fix
send code
anyone?
if message_content.startswith('>pfp'):
preview = link_preview("https://anilist.co/user/LumpiaAce")
print("image:", preview.image)
await message.channel.send(preview.image)
hi guys, I'm creating a translation command, and I wish that when the bot translates the language it does it inside an embed, I just don't know how to do it.
here my code
async def translate (ctx, lang_to, * args):
lang_to = lang_to.lower ()
if lang_to not in googletrans.LANGUAGES and lang_to not in googletrans.LANGCODES:
raise commands.BadArgument ("This language does not exist.")
text = '' .join (args)
translator = googletrans.Translator ()
text_translated = translator.translate (text, dest = lang_to) .text
await ctx.send (text_translated)```
do u put functions inside cog class or outside it
for now there are only functions, I have not created any embed
does ur code work
yes
then u just need to create a discord embed
and
replace ur last line
await ctx.send (text_translated)
with this
embed = discord.Embed(description=text_translated)
await ctx.send(embed=embed)
ok
why doesnt this work
ok, works tysm
oh np
it doesnt read the prefix all the time
any help?
if, on the other hand, I also want to put the language that the user requested?
eg:
[THE LANGUAGE REQUIRED HERE]
text here
[THE LANGUAGE OF THE TEXT]
i dont understand
oh ok
how do i set webhook avatar
i tried giving it a https link tho it showed startswith first arg must be str or a tuple of str, not bytes
i also gave it the Asset cls ie the ctx.author.avatar_url
tho same error
ctx.author.avatar.url if u r on 2.0
UnboundLocalError: local variable 'island_level' referenced before assignment```
Anyone?
Define the variable?
how do i constantly check the prefix
wdym\
I think it always those
profile = await self.bot.profiles.find_one({"_id":ctx.author.id})
inv = await self.bot.invs.find_one({"_id":ctx.author.id})
money, materials_name, materials_value = self.bot.req[building_name]
money = (island[building_name]+1)**2**island_level
if profile["money"] < money:
await ctx.channel.send(f"{ctx.author.mention} You don't have enough coins ({money:,}{self.bot.item_emoji['coin']}).")
return False
And where do you define island_level
Yea but wheres that
Well you need to define it as a variable in your code. THe code you gave doesnt define it
so i have this function,
but it checks only for the first time. when i change it and try doing another command it wont read the new prefix
How to type a username without a mention or discriminator?
I used to know. Now I forgor.
Ya mean this one?
{member.name}
but it just says the id
no the "ctx.author"
Heres a correct example, although its json instead:
https://github.com/MenuDocs/Discord.PY-Tutorials/blob/Episode-9/bot.py#L16
bot.py line 16
def get_prefix(bot, message):```
@slate swan
@client.event
async def on_member_join(member):
global hasloo
haslo = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
haslo2 = 5
hasloo = "".join(random.sample(haslo,haslo2))
channel = guild.get_channel(828011225292079124)
await channel.send(f"**{member.name}, użyj komendy** `!verify (kod)`\n**Twój kod weryfikacyjny to** \n`{hasloo}`")``` channel = guild.get_channel(828011225292079124)
NameError: name 'guild' is not defined
yea but i use text file
anyways, ill use json
Im sure you can figure it out
did u import guild?
import guild ?
{ctx.author.member.name} idek if its gonna work i just put it together
Idk loop it ig
XD
Import guild...?
yes
from discord import guild
How can I make slash commands?
sorry i made a mistake
member.guild should work
o thanks
No...
chat so fast, damn
Sometimes
idk the problem in his code. sorry.
a no work
ch = await self.create_dm() File "C:\Users\Uzytkownik\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\member.py", line 142, in general return await getattr(self._user, x)(*args, **kwargs) AttributeError: 'ClientUser' object has no attribute 'create_dm'
Install discord-py-slash-command
that is a new error :/
then check the documentation, that'll work
yes
money = (island[building_name]+1)**2**island_level
UnboundLocalError: local variable 'island_level' referenced before assignment
def count_reacts(msg):
count = 0
rlist = msg.reactions
for react in rlist:
count = count + 1
return int(count)
this doesn't count reactions properly and instead returns 1 everytime it's called?
you assigned it inside command, it can't be used outside of it like that
return prefixes[str(message.guild.id)]
KeyError: '903281738686562314'```
getting this error
@candid ore , I recommend writing your own code from scratch instead of copy pasting random code
can anyone help?
Well erm.
because you reset it to 0 at the start
screw it, ill figure it out eventually.
You gotta look at a tutorial
I figured that out, but I can't get it working with cogs
what? it's being reset before the loop
well... you say x = 0
oh wait, did I misunderstood that?
and then I add 1 to x for every reaction
try to print len of rlist = msg.reactions
you can either, create a class instance, use global var, botvar.
dont copy code xD
?
lmao im too lazy
i did this like an year ago
the changeprefix
your supposed to get the guild first using bot.get_guild()
what is that id tho
a keyerror
ur looking for something that doesnt exist
!e
a = {"1": "one"}
print(a["a_key_error"])
@boreal ravine :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | KeyError: 'a_key_error'
^
Did I install too old 2.0 version of dpy?
assets are .url now in < 2.0
I have a server info command and one part of it looks like this. How would I put this to the end of it as well? https://www.toptal.com/developers/hastebin/kotorifowa.csharp
not this problem
meaning?
returns 1
even though there are 2 reactions
p.embed.set_author(name=member.display_name, icon_url=member.display_avatar.url)
O okey
!d discord.Member.display_avatar @tough wagon xD
property display_avatar: discord.asset.Asset```
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.
i need
Can someone help
There is just 1 reaction
wdym
I mean that I installed git repo when there wasnt display_avatar in it
when oh
There is no old version of 2.0, is there?
display_avatar new in 2.0
nope
he did .url
i dont think that works
nvm xd
I cant remember
@tawdry perch what do ya want?
@client.command()
async def profile(ctx, member:discord.Member=None):
if member == None:
member = ctx.author
image = member.avatar_url
created_at = member.created_at.strftime("%A, %B %d | %Y | %H:%M:%S %p")
joined_at = member.joined_at.strftime("%A, %B %d | %Y | %H:%M:%S %p")
userid = member.id
roles = member.roles
roles = ', '.join([role.mention for role in member.roles])
embed = discord.Embed(
title = "User Profile",
description = f"{member}",
colour = discord.Colour.purple()
)
embed.set_footer(text=f"ID: {userid}")
embed.set_thumbnail(url = image)
embed.set_author(name= member, icon_url=image)
embed.add_field(name="Roles", value=roles)
embed.add_field(name= "Created account at:", value=created_at, inline=False)
embed.add_field(name= "Joined Server at:", value=joined_at, inline=False)
await ctx.send(embed=embed)```
u may find something usefull in here ig. this my profile code
Pardon?
?
useful ty
366 messages
Ok?
no there isn't
there are two
yet it returns 1
may I send you the server link where I'm testing the bot?
No you can't
ok lemme get a ss
how can i set back the channel perm to default ? like make it back to neutral
ok nvm, it just started working @tawdry perch
even though I didn't change anything
🗿
Good that it works!
how to make the messages that the bot deleted and not the user entered write to a variable and output it
Do what..?
well, the messages in the channel 2 + 1 are command and when I enter commands into the parameter I write 5 and so that 3 and not 5 are output
Sorry for English I'm Russian
@bot.command()
async def infoo(ctx, member:discord.Member=None):
if member == None:
member = ctx.author
created_at = member.created_at.strftime("%A, %B %d | %Y |%H:%M:%S %p")
joined_at = member.joined_at.strftime("%A, %B %d | %Y | %H:%M:%S %p")
embed=discord.Embed(title="Cursex", description="**Identifitcation Card**", color = 0x5865f2)
embed.add_field(name="User's name:", value=f"{member.name}", inline=False)
embed.add_field(name="User's tag:", value=f"{member.discriminator}", inline=False)
embed.add_field(name="User's ID:", value=f"{member.id}", inline=False)
embed.add_field(name="Guild creation date:", value=f"{ctx.guild.created_at.strftime('%A, %B %d %Y @ %H:%M:%S %p')}", inline=False)
embed.add_field(name= "Created account at:", value=created_at, inline=False)
embed.add_field(name= "Joined Server at:", value=joined_at, inline=False)
File "main.py", line 197, created_at = member.created_at.strftime("%A, %B %d | %Y |%H:%M:%S %p") IndentationError: unindent does not match any outer indentation level
Hi guys, I'm not using discord.py a lot, but how can I manage to get a display like this ? I'm only using classic await for now and want to get a result like this. Thanks for any answer
you have not indented the test
@client.command()
@commands.has_role("Report Managers")
async def report_taken(ctx, message_id : discord.Message.id) :
if message_id is None :
await ctx.send("Syntax : er!report_taken <message_id>")
else :
help_log = client.get_channel(help_log_channel)
report_message = await help_log.fetch_message(id)
if report_message.author is client.user :
await report_message.reply(f"Report case taken by {ctx.message.author}")
else :
await ctx.message.reply("That is not my message. Maybe you got the wrong message id?")
``` throwing error
?
converting to id failed for parameter message_id
remove the tab space
and add it again
it will now throw error
but of joined_at
?
then do the same with joined_at remove all spaces and add tab space
sorry i cant undrestand
wdym?
is it your question?
i don't understand
my question is
@bot.command()
async def infoo(ctx, member:discord.Member=None):
if member == None:
member = ctx.author
created_at = member.created_at.strftime("%A, %B %d | %Y |%H:%M:%S %p")
joined_at = member.joined_at.strftime("%A, %B %d | %Y | %H:%M:%S %p")
embed=discord.Embed(title="Cursex", description="**Identifitcation Card**", color = 0x5865f2)
embed.add_field(name="User's name:", value=f"{member.name}", inline=False)
embed.add_field(name="User's tag:", value=f"{member.discriminator}", inline=False)
embed.add_field(name="User's ID:", value=f"{member.id}", inline=False)
embed.add_field(name="Guild creation date:", value=f"{ctx.guild.created_at.strftime('%A, %B %d %Y @ %H:%M:%S %p')}", inline=False)
embed.add_field(name= "Created account at:", value=created_at, inline=False)
embed.add_field(name= "Joined Server at:", value=joined_at, inline=False)
this write
wait
you notice that if is on different level and created_at and joined_at are on different level
the space in created_at and joined_at is not equal to all other keywords
please?
help
disnake.ext.commands.errors.NoEntryPointError: Extension 'cogs.game' has no 'setup' function. ```
i have setup function in the cog.
am using disnake ;-;
got it
and
i dont know how to fix it then
oh ok
use pycord if u know how to use discord.py pycord is best
u dont have to learn different syntax or change your code
nah people say cogs is in disnake is just as in discord.py. The point is i forgot cogs
this is what my dict looks like
this is main.py
oh wait i forgot to import in the cogs
Is it possible to do this?:
create a text channel (i already did)
send a message on this channel (i need know)
why wouldn't it be possible
i know that's possible, but i don't know how do i can do
channel = ... #create text channel
await channel.send("Hey")
its simple like this?
but in my code i used this
await bot.wait_for("reaction_add", check=check)
await guild.create_category("Tickets", overwrites=None, reason=None)
await guild.create_text_channel(name=f'Ticket of {ctx.author.name}')```
and I think it's not possible to add this
channel = await guild.create_text_channel(name=f'Ticket of {ctx.author.name}')
bro even when i use normal dpy this error discord.ext.commands.errors.NoEntryPointError: Extension 'cogs.game' has no 'setup' function.
read it
no setup function
bot.add_cog(Cog_Name(bot))```
forgot this
.-.
i can read .-.
why is it indented
its not
it's supposed to be out of the cog
thats just vsco-
btw that "game" is actually "Game"
Hi guys, I'm not using discord.py a lot, but how can I manage to get a display like this ? I'm only using classic await for now and want to get a result like this. Thanks for any answer
It's discord
you named it game and added Game
that's kinda nice
it still didnt work
lowercase bro
There's a module that makes stats show like that, forgot what it's called since I never used it before
It's likely just an image you need to generate somehow
game != Game
with "g" uppercase it didnt work bro
i know, i already know python smh
gave up
Pretty sure it's numpy but idk if u can put a graph from numpy in an embed message
Name your class with G, classes should start with uppercase letters, and in your setup you alps have it with G not g, also make sure you save and restart
It's not numpy, it's another lib but forgot what the name was
OH WAIT I DONT HAVE AUTOSAVE ON
Lmao
LOL
🤦♂️
Well, I don't know then haha I only used Numpy for stats
Also you can add a graph from numpy as long as you manage to make it into an image file, using PIL and pasting whatever numpy gives should work (probably)
uh, seems like a pain
@bot.command()
async def bal(ctx):
await open_account(ctx.author)
users = get_FD_data()
user = ctx.author
pocket_amt = users[str(user.id)]["pocket"]
FD_amt = users[str(user.id)]["FD"]
embed = discord.Embed(title=f"{ctx.author.name}", color=0xcf24ff)
embed.add_field(name="pocket", value=f"{pocket_amt}")
embed.add_field(name="FD", value=f"{FD_amt}")
await ctx.send(embed=embed)
async def open_acocunt(user):
users = get_FD_data()
if str(user.id) in users:
return False
else:
users[str(user.id)]["pocket"] = 0
users[str(user.id)]["FD"] = 0
with open("bank.json", "w") as f:
json.dump(users,f)
return True
async def get_FD_data():
with open("bank.json", "r") as f:
users = json.load(f)
return users
error:
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
help please
get_FD_data() needs to be awaited since you defined it as async
changing async def to await?
await get_FD_data()...
with open("bank.json", "r") as f:
IndentationError: unexpected indent
error
can i get source code of python bot
So I have coded an AI Chat Bot and there is one thing wrong
hold on let me get the screenshot and code
Python & indetation is something inherent. You should be able to fix this otherwise you should learn some more python before continuing. It'l save you a lot of headaches
!resource
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
alright
thanks
wait thast resource
do we need to get memeber object from ctx.author for adding roles and stuff ?
!source
No, it will already be member if its in a guild
oki
So the bot says the message and then the response time which I don't want. I only want it to say the message like "You are very wise" not that
data[0]['message']
from discord.ext import commands
from prsaw import RandomStuff
from keep_alive import keep_alive
bot = commands.Bot(command_prefix = ">")
api_key = "My API"
rs = RandomStuff(async_mode = True, api_key = api_key)
@bot.event
async def on_ready():
activity = discord.Game(name="Chatting with Y'all!", type=3)
await bot.change_presence(status=discord.Status.online, activity=activity)
print("Bot is ready!")
@bot.event
async def on_message(message):
if bot.user == message.author:
return
if message.channel.id == Channel ID:
response = await rs.get_ai_response(message.content)
await message.reply(response)
await bot.process.commands(message)```
Its a list of dict, so index the list to get what you want, then use the correct key for the dict
For me?
Yea
Alright hold on
@valid perch not working it keeps saying 'invalid syntax' when I place it. Where do you think I should put that code?
That didn't work the bot isn't responding when placed there
show ur updated code
from discord.ext import commands
from prsaw import RandomStuff
from keep_alive import keep_alive
bot = commands.Bot(command_prefix = ">")
api_key = "My API"
rs = RandomStuff(async_mode = True, api_key = api_key)
@bot.event
async def on_ready():
activity = discord.Game(name="Chatting with Y'all!", type=3)
await bot.change_presence(status=discord.Status.online, activity=activity)
print("Bot is ready!")
@bot.event
async def on_message(message):
if bot.user == message.author:
return
if message.channel.id == Channel ID:
response = await rs.get_ai_response(message.content)
await message.reply(response)
await bot.process.commands(message)```
Changed everything back
to the way it was
This is what i don't want it to say
Show the code...? I can't read your mind
rs.get_api_responce returns a dict inside a list, so you need to index it
I provided the code as well haha, oop. They just had to change a variable name and put it in the right place which aint hard
Yea, but will wait for more code to help
.guild
ok i tryy....
client = discord.Client()
await client.get_channel(898274639913058349).send("Test")
Someone knows why I can't get the channel ? I got a NoneType instead of it
Already checked if my bot have access to the channel
You can't run async code unless its in an async function
it returned nonetype
And the cache (which get_ uses) isn't populated until the bots logged in and ready
so we already know that that's not the case
It is in but I'm not sending the whole function
try fetch_channel
I'm trying it, thanks
Then if it errors itll provide more info
my gramm
Because your looking at the wrong thing, and I can't help without code
i send
@client.command(pass_context=True)
async def play(ctx, url):
server = ctx.message.guild
voice_client = client.voice_client_in(server)
player = await voice_client.create_ytdl_player(url, after=lambda: check_queue(server.id))
players[server.id] = player
player.start()```
Make it two lines
@valid perch
no
Doesn't exist there mateo
So use the link to get the guilds voice client
Could also just use ctx.guild.voice_client
client = discord.Client()
channel = client.fetch_channel(898274639913058349)
await channel.send("Test")
Something like that ? Tried and I still got the same error :/
await fetch_channel
Sorry went afk how did you do it? I'm just a bit new to bot coding so I don't know what indexing is...
I suggest learning more python first, discord bots are not begginer friendly and it'll remove lots of headaches
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
client = discord.Client()
await client.fetch_channel(898274639913058349).send("Test")
Something like that ?
i'll read it
Are you a beginner Discord bot developer?
client = discord.Client()
channel = await client.fetch_channel(898274639913058349)
await channel.send("Test")
Yup, I'm used to use Python but I'm not using a lot of async/await things
how do i send a message when the bot runs into the error of not having permissions
client = discord.Client()
await (await client.fetch_channel(898274639913058349)).send("test")
handle the error using the on_command_error handler or per command handler.
yeah i have it for when a command is ivalid but i can't get it to work for other commands
what
Then I recommend learning asynchronous programming in Python with asyncio and read the documentations for the library you are using. If you're using discord.py, a bot should be instantiated from discord.ext.commands.Bot. It has commands and command & error handling (even a built-in help function)
@client.event
async def on_command_error(ctx, error):
if isinstance(error, CommandNotFound):
embed=discord.Embed(title="**Error** :important:", color=0xff0000)
embed.clear_fields()
embed.add_field(name="Command Error", value="The provided command does not exist. Please take a look at the existing commands via the help menu.", inline=False)
embed.set_footer(text="Made with love and care by Need_Not and Mrgoldy")
await ctx.send(embed=embed)
if isinstance(error, BotMissingPermissions):
ctx.send("i dont have the permission to do that")```
2nd one doesn't work
Why is the button with id 4 not working?
where do i look
ig ur importing the first error from discord.ext.commands so do commands.BotMissingPermissions
how can I create a channel within a category?
do u put functions outside of cog class or inside
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.
The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
@client.event
async def on_member_join(member):
global hasloo
haslo = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
haslo2 = 5
hasloo = "".join(random.sample(haslo,haslo2))
gildia = client.get_guild(656203782144917525)
channel = gildia.guild.get_channel(828011225292079124)
await channel.send(f"**{member.name}, użyj komendy** `!verify (kod)`\n**Twój kod weryfikacyjny to** \n`{hasloo}`")```
File "C:\Users\Uzytkownik\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 343, in _run_event await coro(*args, **kwargs) File "c:/Users/Uzytkownik/Desktop/Dawid Orginalny/Python/avexy veryfi/main.py", line 73, in on_member_join channel = gildia.guild.get_channel(828011225292079124) AttributeError: 'Guild' object has no attribute 'guild'
wtf are you doing?
do you know how get_channel works?
I don't know, they told me to do this and it still doesn't work, I just want a message to be sent when the member is done
its as simple as just doing member.channel.send, why are you doing all that
A
Because that's what they recommended to me
so
do u put functions in cogs class or outside
replace gildia.guild.get_channel with gildia.get_channel
File "C:\Users\Uzytkownik\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\member.py", line 142, in general
return await getattr(self._user, x)(*args, **kwargs)
AttributeError: 'ClientUser' object has no attribute 'create_dm'
no dm
Command raised an exception: PermissionError: [Errno 1] Operation not permitted what is this?
he does not even need to do that, he can just do member.channel.send
mhm
send the whole error
await member.channel.send(f"**{member.name}, użyj komendy** !verify (kod)\n**Twój kod weryfikacyjny to** \n{hasloo}") AttributeError: 'Member' object has no attribute 'channel'
wait
ok
ah its member.guild.channel.send
a
Orrrr hear me out
await member.send
like this ?
gildia = client.get_guild(656203782144917525)
channel = gildia.guild.get_channel(828011225292079124)
await member.guild.channel.send(f"**{member.name}, użyj komendy** `!verify (kod)`\n**Twój kod weryfikacyjny to** \n`{hasloo}`")
await channel.send
gildia.guild.get_channel(828011225292079124) -> gildia.get_channel(828011225292079124)
Ignoring exception in on_command_error
Traceback (most recent call last):
File "/home/Mechanic/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/Mechanic/cogs/samp.py", line 91, in addserver
serverName = getServerName(client)
File "/home/Mechanic/scwrapper.py", line 4, in getServerName
info = client.get_server_info()
File "/home/Mechanic/sampclient/client.py", line 62, in get_server_info
response = self.send_request(OPCODE_INFO)
File "/home/Mechanic/sampclient/client.py", line 46, in send_request
self.socket.sendto(body, (self.address, self.port))
PermissionError: [Errno 1] Operation not permitted```
ye
oke
aint that for dms tho
True
you want a command that sends something to the person that joins a server?
@valid perch
I don't want anything
bruh atleast know whos he talking to
who is it
i know who he is talking to?
i can't help??
then why did you ask him wtf?
i thought it was him that needed help
why are you getting so mad?
is there a message:discord.Message?
channel = gildia.guild.get_channel(828011225292079124)
AttributeError: 'Guild' object has no attribute 'guild'
it sounds like i am but im actually not lmao
ok
@kindred epoch
remove channel = gildia.guild.get_channel(828011225292079124)
oke oke
anyone?
i actually have no idea, never encountered this error, but looks like some permission error
what do you mean
yes
(ctx, message:discord.Message=None)
ok ,ty
channel is no use?
no
what editor are you using
visual studio code
that works for you? damn
yes
discord perms or what?
i had to remove those 2
What should I arrange
ofc from replit import db wont work cuz its not replit
i know it won't work
but it is what is is
@magic stump remove pic
o fck
reset token
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
okey
dałna z tym dostaje
File "c:/Users/Uzytkownik/Desktop/Dawid Orginalny/Python/avexy veryfi/main.py", line 73, in on_member_join await member.guild.channel.send(f"**{member.name}, użyj komendy**!verify (kod)\n**Twój kod weryfikacyjny to** \n{hasloo}") AttributeError: 'Guild' object has no attribute 'channel' ```py
hasloo = "".join(random.sample(haslo,haslo2))
channel = member.guild.get_channel(828011225292079124)
await member.guild.channel.send(f"**{member.name}, użyj komendy** `!verify (kod)`\n**Twój kod weryfikacyjny to** \n`{hasloo}`")```
but
member.guild returns Guild object
But seems like you've already fetched the channel on the line above
So you can just use that to send the message right
how do i fix this never seen this error before
typeerror: client.event() missing 1 required argument: 'coro'
https://paste.pythondiscord.com/esivekukic.py
mhm
channel.send?
It's @client.event
Without bracks
Exactly
ok i understand now
a oke
Great!
but i have an @ in it
Ignoring exception in on_message Traceback (most recent call last): File "C:\Users\Uzytkownik\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 343, in _run_event await coro(*args, **kwargs) File "c:/Users/Uzytkownik/Desktop/Dawid Orginalny/Python/avexy veryfi/main.py", line 39, in on_message await message.author.send(embed=embed1) File "C:\Users\Uzytkownik\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\abc.py", line 1013, in send channel = await self._get_channel() File "C:\Users\Uzytkownik\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\member.py", line 299, in _get_channel ch = await self.create_dm() File "C:\Users\Uzytkownik\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\member.py", line 142, in general return await getattr(self._user, x)(*args, **kwargs) AttributeError: 'ClientUser' object has no attribute 'create_dm'
i just relooked at it
Yeah you do, that doesn't mean () are necessary
Show code
@client.event
async def on_member_join(member):
global hasloo
haslo = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
haslo2 = 5
hasloo = "".join(random.sample(haslo,haslo2))
channel = member.guild.get_channel(828011225292079124)
await channel.send(f"**{member.name}, użyj komendy** `!verify (kod)`\n**Twój kod weryfikacyjny to** \n`{hasloo}`")```
Oh
oh so i need to remove them from the end got it
cool thanks on that fix but another problem is this the async is red in vscode https://paste.pythondiscord.com/umawacohon.py
how you get my all code
I don't want it
It's in the on message event, check for the error sir
Brb, battery
how do i get the bots prefixs?
wdym you mean create one or how to get them to see what prefixes you have?
aaaaaaaaaaaaaaaa
working ty bro
@client.event
async def on_message(message):
channel = (828011225292079124)
if message.channel.id == channel and message.content != "!verify":
await message.delete()
embed1=discord.Embed(title="Błąd", color=0xff0000,timestamp=datetime.utcnow())
embed1.add_field(name="\u200b", value="**Użyj komendy !verify aby się zweryfikować! **", inline=False)
embed1.set_thumbnail(url = "https://emoji.gg/assets/emoji/1326_cross.png")
await message.author.send(embed=embed1)
await client.process_commands(message)``` How to do here not to delete bot messages?
?
you want the bot to delete a message?
the message it sent?
if so
@client.event
async def on_message(message):
channel = (828011225292079124)
if message.channel.id == channel and message.content != "!verify":
await message.delete()
embed1=discord.Embed(title="Błąd", color=0xff0000,timestamp=datetime.utcnow())
embed1.add_field(name="\u200b", value="**Użyj komendy !verify aby się zweryfikować! **", inline=False)
embed1.set_thumbnail(url = "https://emoji.gg/assets/emoji/1326_cross.png")
await message.author.send(embed=embed1, delete_after=time) # Time must be an int and its in seconds
await client.process_commands(message)
So that he does not delete the messages he sends about
no its not
well i got that to work in my purge command
delete_after=True is stupid imo
delete_after=time_in_int is better
please dont tell people false info mate
using that is not efficient
ok i'll leave it for you then just trying to help
np
uh this may be a stupid question so apologies, but im trying to make a bot that can get data from AniList and after some research i found an API for it. However I do not know what to do with it :/ does anyone have like a guide ig i can read or smthn to learn how to use an API
heres the API: https://github.com/AniList/ApiV2-GraphQL-Docs/tree/master/book
so
this work?
if message.channel.id == channel and message.content != "!verify" or client.message:``` i want to no delete message od bota
@magic stump you dont want !verify to delete?
Everything works, it only shows the error when the bot sends a message that it can't
@magic stump bc the users dms are likely closed
but I don't want to dm
^^
you might want
await message.channel.send ()
the user comes to the server and the bot sends to the veryfication channel the verification code that the user must enter now he wants to do if I enter something other than the command! verify
so
how can i send msg if there are 2 words in the msg?
??
@client.event
async def on_message(message):
global s
channel = (828011225292079124)
if message.channel.id == channel and message.content != "!verify" or :
await message.delete()
embed1=discord.Embed(title="Błąd", color=0xff0000,timestamp=datetime.utcnow())
embed1.add_field(name="\u200b", value="**Użyj komendy !verify aby się zweryfikować! **", inline=False)
embed1.set_thumbnail(url = "https://emoji.gg/assets/emoji/1326_cross.png")
await message.author.send(embed=embed1, delete_after=time) # Time must be an int and its in seconds
await client.process_commands(message)
``` i wish abty bot wouldn't delete its messages
what is that or doing in your if statement
I do not know what to put in there so that the bot does not delete its messages
i dont understand what youre trying to do exactly
replace a character
and what does that have to do with discord.py xD
its for a bot
thanks for the help
❤️
Can a message have multiple images?
yes
abc.Messageable.send() has a files keyword-argument
!d discord.TextChannel.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/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.9)") of [`File`](https://discordpy.readthedocs.io/en/master/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/master/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.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
exactly
To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.
Yeah ive been doing single images but recently learnt multiple is possible 🤭
msg = await ctx.channel.send(f"`Now playing: {var3}` \n{url}")
await msg.add_reaction(u"\u23F8")
await msg.add_reaction(u"\u25B6")
try:
reaction, user = await client.wait_for("reaction_add", check=lambda reaction, user: reaction.emoji in [u"\u23F8", u"\u25B6"], timeout=90.0)
except asyncio.TimeoutError:
return await msg.clear_reactions()
else:
if reaction.emoji == u"\u23F8":
await msg.remove_reaction(reaction.emoji, ctx.author)
await ctx.voice_client.pause()
elif reaction.emoji == u"\u25B6":
await msg.remove_reaction(reaction.emoji, ctx.author)
await ctx.voice_client.resume()
This code is supposed send a message showing what is playing, and bring up pause and play reactions which will pause and play the audio when reacted to by a user. Right now it only responds to a reaction once, for example if someone hits the pause emoji then the audio will be paused, however if the play emoji is hit after that then nothing will happen.
how do i add badges into the summary of who someone is?
@bot.command()
async def info(ctx, member:discord.Member=None):
if member == None:
member = ctx.author
created_at = member.created_at.strftime("%A, %B %d | %Y | %H:%M:%S %p")
joined_at = member.joined_at.strftime("%A, %B %d | %Y | %H:%M:%S %p")
badges = {
UserFlag.hypesquad_bravery: ":Braverylogo:899689315083366430",
UserFlag.hypesquad_brilliance: ":Brilliancelogo:",
UserFlag.hypesquad_balance: ":Balancelogo:",
UserFlag.verified_bot_developer: ":verifitedbotdeveloperlogo:",
UserFlag.bug_hunter: ":Bughunterlogo:",
UserFlag.bug_hunter_level_2: ":Bughunterlevel2logo:",
UserFlag.early_supporter: ":earlysupporterlogo:",
UserFlag.staff: ":stafflogo:",
UserFlag.discord_certified_moderator: ":certifiedmoderatorlogo:"}
allbadges = [badges[flag] for flag in member.public_flags.all()]
embed=discord.Embed(title="Cursex", description="**Identifitcation Card**", color = 0x5865f2)
embed.add_field(name="User's name:", value=f"{member.name}", inline=False)
embed.add_field(name="User's tag:", value=f"{member.discriminator}", inline=False)
embed.add_field(name="User's ID:", value=f"{member.id}", inline=False)
embed.add_field(name"=Badges:", value=f"{member.badges}", inline=False)
embed.add_field(name="Guild creation date:", value=f"{ctx.guild.created_at.strftime('%A, %B %d %Y | %H:%M:%S %p')}", inline=False)
embed.add_field(name= "Created account at:", value=created_at, inline=False)
embed.add_field(name= "Joined Server at:", value=joined_at, inline=False)
embed.set_footer(text=f"Requested by {ctx.author}")
embed.timestamp = datetime.utcnow()
await ctx.send(embed=embed)
would that work?
Hey i need some help. I want to create a roblox verify command and it links a user to their roblox account.
and what do you have?
Well i kinda need an api.
not sure if roblox has one
So i am working on an embed for the invite for my bot and i get an error in vs code when i have this code https://paste.pythondiscord.com/eridojumoc.py about the \n if i do ; it only sends one and , only sends the first line
!pypi roblox
oh
here let me re write it for you
do you want me to explain it?
wait
you might want to google some things for that
that was just some random guess
Try out that code
Title and Description should be in embed=discord.Embed(title="e", description='e')
it was my product i was getting was this i just need to have a new line made
Ok?
and it didn't like it
Ohhh
Is it working now or
so i just need help gettign a new line made
that is what i had before
i asked i wanted to add another invite link but the line wouldn't create for the new one
So is it work ing or
and i did \n in another part just fine
the new code i sent
it is working half
try this out https://paste.pythondiscord.com/gukiqufaki.py
ok
I forgot the f
You can continue with it and put the /n
Hey, does anyone know the steps we need to take to track when a user is and isn't speaking in a VC?
I know the bot needs to be in the VC but not sure if there are events for this or if we have to parse some ws stream
Now try this; https://paste.pythondiscord.com/pesuyoxute.py
@echo wasp
k
i dont think you can do that
and if you can, discord.py does not support that
^^^
Let me check.
no vc ws conn?
nope
i got the purge and invite link embed working now from yesterday
good
yes and that woked
why won't my code replace user.mention?
user = ctx.author
if "{user.mention}" in message:
message = message.replace("{user.mention}", user.mention)
damn 2018
when using discord embeds, it should be like this: embed=discord.Embed(title="Title Here", description="Description here"). And when using \n it should be like await ctx.send("hey \n hi")
your forgot the f string
user = ctx.author
if "{user.mention}" in message:
message = message.replace(f"{user.mention}", user.mention)```
Just remember when trying to use {} inside of a "" make sure its f"{ctx.mention}"
np
nice i'll take note
taken note of
return await message.edit("You have not added any servers.")
TypeError: edit() takes 1 positional argument but 2 were given```
what did i do wrong?
Np
await message.edit(content="newcontent")
ah
np
If I want to put the bot on herok hosting, do I have to delete the last line?
Nope.
Nope! Are you having problems with hosting on Heroku? If so, what’s the issue?
Do you know hot to put it on Heroku? is there an error?
yes
Ah, what issue are you getting?
No that’s fine. Do you have a Procfile in your repo?
yes
How about a requirements.txt
:)\
Could you post an image of your repositories files? not the file content, just the files
this?
It seems like you don't have a Procfile
heroku requires a Procfile to run I believe
profil
on githhub?
so you would add a file just called Procfile and in there you would write worker: python main.py
Yep!
okey
It would be Procfile, I think you forgot the c
Can you take a larger picture so I can see the error?
Like could you take a larger photo to the right?
I don't know if there is a bug, but it is offline
It cuts off at "state changed from starting.."
what
umm so i have multiple servers my bot is in but it only shows the members of one of the servers not both how do i fix that? and it it only shows one server with id that it is connected to **Code:**https://paste.pythondiscord.com/sohorudemi.py Ping me if you got a fix for that
Those are called slash commands!
It seems like you'll need to run it as a "task in the background"
https://devcenter.heroku.com/articles/one-off-dynos#running-tasks-in-background
There is a way to check whenever a role is added to a member?
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change:
• nickname
• roles
• pending...
yes
yes
It seems like you're breaking right after you find the guild you want (guild == DISCORD_GUILD), and so now guild is only equal to that guild. You'd want to fix this via printing with the code instead the for loop and not break out
so how do I fix that? someone else help me set it up I have more code down bellow but that part bugs me
The following code:
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})\n'
)
members = '\n - '.join([member.name for member in guild.members])
print(f'Guild Members:\n - {members}')
should go in the for loop, so that you're printing it from each guild and not just breaking out and getting one guild
10-4
o error
so above where it does the break is that fine?