#discord-bots
1 messages · Page 433 of 1
Hey @prisma wedge!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
i cant send itr
tryguild.fetch_message() or client.fetch_message()
!paste use hastebin
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.pydis.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.
fetch_message is a method of a TextChannel object
what do i do now
AttributeError: 'Bot' object has no attribute 'fetch_message'
How can I check a channel description to see if it includes a specific word?
did the url change, if so share the url here
sorry what does that mean i need to do lol?
I edited it.
someone?
First get the channel that the message is in, then fetch the message
please?
but guild.fetch_message() ?
Ah wait, didn't read the whole message here
You might be able to just get the context object and use it
But @uncut comet, what are you trying to do?
Hello all!
I have an issue where as a ' ' wont replace with '%20'. I'm fetching a span from a site, it works, but I need the command to work like >stats SEN TenZ 0001 and not >stats SEN%20TenZ 0001. I have to manually add the %20 for a space instead of a real one.
@client.command()
async def stats(ctx,username: str,tag: str):
username.replace(" ", "%20")
URL = f"https://tracker.gg/valorant/profile/riot/{username}%23{tag}/overview?playlist=competitive&season=all"
URL2 = f"https://tracker.gg/valorant/profile/riot/{username}%23{tag}/overview?playlist=competitive"
if ' ' in username:
username.replace(" ", "%20")
page = requests.get(URL, URL2)
soup = BeautifulSoup(page.content,"html.parser")
results = soup.find("span", {"class":"valorant-highlighted-stat__value"})
rank = results.text
ok so
async def check_role(user, level, plus):
with open('roles.json', 'r') as f:
roles = json.load(f)
for i in range(len(roles)):
if not roles[str(level)]:
print(f"no role for level {i}")
else:
await user.add_roles(roles[str(level)])```
this is supposed to auto role on level up
but it causes a loop
async def level_up(users, user, channel, server):
experience = users[str(user.guild.id)][str(user.id)]['experience']
level_start = users[str(user.guild.id)][str(user.id)]['level']
level_end = 25 * (2 * (level_start+1)**2 + (level_start+1))
if str(user.guild.id) != '757383943116030074':
print(experience)
print(level_end)
if int(experience) >= int(level_end):
await channel.send('{} has leveled up to Level {}'.format(user.mention, level_start+1))
users[str(user.guild.id)][str(user.id)]['level'] = level_start+1
plus = True
await check_role(user, level_start+1, plus)```
and commands stop working
im trying to make an embedder but i cant figure out how can i separate the title from the msg
@client.command()
async def update(ctx, *, title, msg):
embed = discord.Embed(title=f"**{title}**", description=f"{msg}", color = 0xFFFF00)
await ctx.send(embed=embed)
await asyncio.sleep(0.1)
await ctx.message.delete()
What do you mean by separate?
like
if i just do
*update <title> <msg>
it will miss the msg and put it as a title
id assume the whole argument is taken as the title, according to how their parameters are set up.
yep
so what can i do to separate the title and the msg
this doesnt work so im still confused
end = datetime.utcnow()+timedelta(seconds=tr).total_seconds()
What part of it dosen't work?
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'float'
Ah, well, that's because you are doing total_seconds() from the timedelta, and trying to subtract it from the datetime
you need to do it from the product of the two
end = (datetime.utcnow()+timedelta(seconds=tr)).total_seconds()
let me try that
is there something i need to import at the top of my code btw @wicked atlas?
Command raised an exception: AttributeError: 'datetime.datetime' object has no attribute 'total_seconds'
bro
i know that one?
How do I get a specific word from a list?
maybe
Like a bad word from a bad word list
i try like an hour
or someone
pls
sorry, one sec
forgot that total_seconds was a timedelta thing
@verbal hill just do .timestamp() instead
?
Where to find colors for embed?
!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.
`x == y` Checks if two colours are equal.
`x != y` Checks if two colours are not equal.
`hash(x)` Return the colour’s hash.
`str(x)` Returns the hex format for the colour.
but customizable
click the link at the top of this embed
doing this:
(datetime.utcnow()+timedelta(seconds=tr)).timestamp()
respons with this:
End: 1630368639.336089
yep, that's a posix timestamp
Just put that into format for discord
<t:1630368639>
Which will come out as <t:1630368639>
ok, can't have the decimal apparently
await user.add_roles(roles[str(level)], reason="leveled up", atomic=False)```
AttributeError: 'int' object has no attribute 'id'
{"2": 881581831814799420}
if its like this:
end = (datetime.utcnow()+timedelta(seconds=timer)).timestamp()
how would i replace the 1630368639 with the variable end
You might need to convert it to an integer, so you don't have the decimal at the end
When doing things like adding roles, you don't always need the whole role object. Just create a snowflake:
await user.add_roles(discord.Object(id=role_id))
can someone help me with this?
embed = discord.Embed(title=f"**{title}**", description=f"{msg}", color = 0xFFFF00)
embed.add_field(title= "something", value = msg)
await ctx.send(embed=embed)
await asyncio.sleep(0.1)
await ctx.message.delete()```
I'm making an embed and in the author part how would I put their pfp
@commands.command(aliases=['av'])
async def avatar(self, ctx, *, member: discord.Member=None):
if not member:
member = ctx.message.author
embed=discord.Embed(title="**Avatar Command**",
description="Returns with avatar of a user or yourself",
color=0xff0000)
embed.set_author(name=f"{member}" )
await ctx.send(embed = embed)
icon_url=ctx.author.avatar_url
what?
This is what I have so far
To the right of my name I would like to have the users pfp
Heyho! I want to get all existing channel permissions in a list without having to type them out manually. Is that possible?
Like manage_channel and so on
well, thats set_thumbnail
so embed.set_thumbnail(url = member.avatar_url)
import discord
from discord.ext import commands
import asyncio
import json
import os
import traceback
import logging
import sys
#Discord client constructor
intents = discord.Intents.default()
client = commands.Bot(command_prefix=json.load(open('./config.json', 'r'))['Prefix'], intents=intents)
client.remove_command('help')
#Setup Discordpy Warning Logging
dpylogger = logging.getLogger('discord')
dpylogger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='./logs/dpylogger.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s'))
streamhandler = logging.StreamHandler()
streamhandler.setLevel(logging.WARNING)
streamhandler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s'))
dpylogger.addHandler(handler)
dpylogger.addHandler(streamhandler)
# Setup Main Python Logging
logger = logging.getLogger('main')
logger.setLevel(logging.DEBUG)
mainfilehandler = logging.FileHandler(filename='./logs/mainlogger.log', encoding='utf-8', mode='w')
mainfilehandler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s'))
strhandler = logging.StreamHandler()
strhandler.setLevel(logging.INFO)
strhandler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s'))
logger.info('Loading Cogs')
#Load Cogs
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
try:
client.load_extension(f'cogs.{filename[:-3]}')
except (ImportError, SyntaxError) as e:
logger.fatal(f'Failed to load extension {filename}')
traceback.print_exc(e)
sys.exit(1)
if __name__ == '__main__':
try:
client.run(json.load(open('./config.json', 'r'))['Token'])
except discord.HTTPException:
logger.fatal(f'HTTPException in main loop')
sys.exit(1)
except discord.LoginFailure as lf:
logger.fatal(f'LoginFailure in main loop')
logger.fatal(lf)
sys.exit(1)
``` Am is missing somthing? The logger calls are not working at all, neither are the ones inside my cogs. Is there a special syntax for using logging in cogs?
aight ig that works
ty
@patent lark u know da answer?
Anyone lol? im pulling my hair out
You actually need to add a file or just send it as a message outside the embed if you wanna keep the link
There was a way to make links a file uhhhm
I don't want to keep the link
I just want it to embed into a gif
If anyone knows can they ping me
my code is
@commands.command(aliases=['av'])
async def avatar(self, ctx, *, member: discord.Member=None):
if not member:
member = ctx.message.author
embed=discord.Embed(title="**Avatar Command**",
description=f"Returns with avatar of a user or yourself.\n\n**Avatar Of**\n`{member}`\n\n{member.avatar_url}",
color=0xff0000)
embed.set_author(name=f"{member}" )
await ctx.send(embed = embed)
Also quick question
Is it possible to remove the default help command
And another question
In the brackets in the async def line what does the * do
Inside bot = Bot() put help_command = None
Basically takes every following argument as one string
Whats the use of it?
If you mean
async def hello(ctx,*,abc)
Well if someone gives multiple arguments like
Hello I am cool
if you only type (ctx,abc), abc would be "Hello", but since theres a * it will be "Hello I am cool" or if there are more arguments (ctx,hello,*,rest)
It would be "I am cool"
thats a bit confusing
Welp thats how it is
Imagine you want to make a...very simple example... !say command, now letting the user do !say hello would give "hello", but if they type !say hello world, itll still be "hello"
Thats why * comes in game
ah
Also in
if not member:
member = ctx.message.author
You should be able to do
member = member or ctx.message.author
iirc
That would make it shorter, just a hint
Second one works yes
Yes it does thank you
Np
Im still tryna figure out how to the the pfp in the top left of the embed
?
!d discord.Embed.set_thumbnail
set_thumbnail(*, url)```
Sets the thumbnail 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/stable/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the thumbnail.
yea uff you were faster
(:
¯\_(ツ)_/¯
I tried to implement it but its returning <cogs.misc_commands.Moderation object at 0x0000010BB23F6820>
this is what I tried doing
embed.set_author(name=discord.Embed.set_thumbnail(self, url='https://cdn.discordapp.com/avatars/669343267589980160/a_c431e2fde24c6136f7c5fac789057227.gif?size=1024'))
Ah, that's now how u do it
embed.set_thumbnail(url='https://cdn.discordapp.com/avatars/669343267589980160/a_c431e2fde24c6136f7c5fac789057227.gif?size=1024')
Then?
set_author(*, name, url=Embed.Empty, icon_url=Embed.Empty)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Could you please explain the url=Embed.Empty
Like what would I put there
U can ignore that. Just put in your icon url in icon_url :)
That works ty!
Cool
Code
@commands.command(aliases=['av'])
async def avatar(self, ctx, *, member: discord.Member=None):
member = member or ctx.message.author
embed=discord.Embed(title="**Avatar Command**",
description=f"Returns with avatar of a user or yourself.\n\n**Avatar Of**\n`{member}`\n\n{member.avatar_url}",
color=0xff0000)
embed.set_author(name=f'{member}', icon_url='https://cdn.discordapp.com/avatars/669343267589980160/a_c431e2fde24c6136f7c5fac789057227.gif?size=1024')
embed.set_footer(text="")
await ctx.send(embed = embed)
Alright
hi how can i make an alias for a command? i've looked through the docs but i don't understand 
@bot.command(aliases=[])
Add them inside the list brackets
hmm how would i do that for a particular command?
I just told you that....?
how do I make only one button work for a role?
oh nvm 
Check or something...?
@bot.command(aliases=["p", "pong"])
async def ping(ctx):
pass```
now p and pong would trigger this command

Yeah I seriously have no idea how to get the url to embed into an image
!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/stable/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
!d discord.Embed.set_thumbnail
set_thumbnail(*, url)```
Sets the thumbnail 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/stable/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the thumbnail.
!d discord.Embed.set_author
set_author(*, name, url=Embed.Empty, icon_url=Embed.Empty)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
(:
!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.
Ok
umm, why is this thing typing for so long...
This is what I was looking for ty
I finally made my avatar command and imo it looks pretty good
its... a bot
Ah, seems like a discord bug.. If it's yours, then restart it. I remember someone telling me that there is a bug in ctx.typing
Idk if it was fixed or not tho
ctx.trigger_typing() ?
i see
Mhm
cant you also use like uh
ctx.channel.typing?
breh, it's the same....
i know
await trigger_typing()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Triggers a *typing* indicator to the destination.
*Typing* indicator will go away after 10 seconds, or after a message is sent.
1 sec
@visual island do u have an eval? If yes, then try sending a message with the eval. Should stop after that
why
it doesnt stop...
did you imported the libraries for slash commands@wheat ember
Weird
huh wait
Mhm
@wheat ember did you define it?
how
just like you do
it stopped for a sec then continues typing....
Lmao
Bot = commands.Bot() there must be something for your slash library too
Restart the bot
ye, it stopped
this pro just failed
Hmm, but that shouldn't really happen cz u r using the context manager...
yea, ikr
Seems like the bug still exists. I'mma see if I can find the root cause of it (possibly won't be able to find it but who knows)
hi does anybody know how the colours for embeds work? what colour format is it in?
Or u sure a command wasn't getting executed?
hex
tenks
Just prefix 0x
how to add slash library?
ok
um... the test command?
not really, @unkempt canyon does that also
whenever i try to run my bot I get this
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Anyone know why?
should be lemme check
IT WAS OFF BY A SPACE
THX
can some one type a work slash command example???
do
@commands.has_any_roles(id1, id2...)```
oh
@slate swan
you can put many ids
!d discord.ext.commands.has_any_role
discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.
Similar to [`has_role()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.
This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
i see
if you use an ID it should be an int not str
but a role name must be a str
let me see your code
that should work fine
send your full traceback error
i see
on_command_error eats errors
what does it tell you?
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\USER\Desktop\ZENESIS DEVELOPEMENT\PYTHON\ZENESIS\WARN SYSTEM [MONGO]\commands\warn.py", line 103, in remove_warn
test = r.orders.find({"guild": ctx.guild.id, "member": member.id}).sort( { "warn": -1 } )
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\motor\metaprogramming.py", line 272, in return_clone
cursor_method(self.delegate, *args, **kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\cursor.py", line 726, in sort
keys = helpers._index_list(key_or_list, direction)
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\helpers.py", line 73, in _index_list
raise TypeError("if no direction is specified, "
TypeError: if no direction is specified, key_or_list must be an instance of list```
@patent lark plz help
hey can anyone help me i want to test my bot
if you can join my server DM me
you can leave after testing```
Guy!!! wat happend to me?
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/stable/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
is there a method for stopping the Context.typing()? Cause it seems that using context manager triggers the typing forever...
No
sad
I already add that
No
You can use async_timeout with async with ctx.typing():
aiohttp?
a lib?
ye
@maiden fable bud can u help me regarding mongo
oh, how about asyncio.wait? should it work?
what about asyncio.wait_for?
it probably behaves the same as async_timeout. no?
not really, no
Sorry bro, I gotta have a bath else I'mma get killed.. Gtg, cya
ah ok bye bud
Cya!
honestly the whole server is full of sql users no mongo user but why
Breh
but how is it bad
MongoDB is a NoSQL database that stores data as documents in BSON format. Not recommended in general as most of Discord data you are storing is relational (e.g. economy things) while mongodb is for non-relational data, hence there is no reason to use NoSQL over SQL to store relational data.
Ignoring exception in command remove_warn:
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\USER\Desktop\ZENESIS DEVELOPEMENT\PYTHON\ZENESIS\WARN SYSTEM [MONGO]\commands\warn.py", line 102, in remove_warn
test = r.find({}, {"guild": ctx.guild.id, "member": member.id}).sort( { "warn": -1 } )
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\motor\metaprogramming.py", line 272, in return_clone
cursor_method(self.delegate, *args, **kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\cursor.py", line 726, in sort
keys = helpers._index_list(key_or_list, direction)
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\helpers.py", line 73, in _index_list
raise TypeError("if no direction is specified, "
TypeError: if no direction is specified, key_or_list must be an instance of list
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: if no direction is specified, key_or_list must be an instance of list
Process finished with exit code -1
someone help
mongo is not bad , it’s not recommendable for certain things, this brings back the JSON discussion, how everyone says JSON is bad, no, json is not bad, it’s just not supposed to be used for database purposes. same with mongo, it’s a database with pros and cons to certain things
@patent lark can u help me with mongo
😆 good one
imma head back to dpy server ill ttyl
avatar_url_as('png', size=4096).url```
send code
Why does this channel still exist
Discord.py isn’t supported anymore 🥲
I’ll miss it
You don't have message defined anywhere. And also that's an on_member_join event, which its parameters are member and self if you are using cogs. If you want to send a message to a channel then get the channel with bot.get_channel(channel id) then send the message to the channel object that returns.
oh
Not until april 2022.
cause this channel is not about dpy only
^
There are many good forks also, (I am also working on one with a friend of mine), so yea, dpy isn't dead
There’s other libraries ?
General discord bot development in python support.
Yups
I am also working on one with a friend of mine
you... you don't invited me
Are they even good…
!pypi dislash.py is a good library for interactions
https://github.com/EQUENOS/dsc.py
This is one of the lib (we are working hard to implement application commands first)
i see
EQ is the developer of dislash.py. I heard in their support server that he is working on a discord.py fork.
Aw, the reason I didn't do it cz u said u will work on the whatsApp API. But you are always invited!
Yups that's the link
JS users are mocking us rn..
i quit :D
Why do you even care? JS and Python are different
Making the whatsApp api?
yeah
maybe later, cause im not really know aiohttp too much
and typing stuffs
Because I got hit by karma after telling JavaScripters they should use python for their bots instead
xd
Eh, just ignore them. Many people mock me too that use JS and that Python isn't the language for bot making... But I just ignore them, cz I know that Python also has the potential to make big bots (like Carl and MEE6, among others).
why does @commands.has_permissions() raise the MissionPermissions exception even though the member has a role that grants the specified permission check?
Iirc, that check for the text channel perms, not the guild perms
ah. thank you
!d discord.ext.commands.has_guild_permissions
discord.ext.commands.has_guild_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.has_permissions "discord.ext.commands.has_permissions"), but operates on guild wide permissions instead of the current channel permissions.
If this check is called in a DM context, it will raise an exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage").
New in version 1.3.
thanks for the alternative
(:
@maiden fable
Yea
Also, about the mongo thing. I haven't really used it, but u can also try asking in #databases (but go on, post the question here also)
tried many times in databases everone's answer is either he dont know or he haven't used mongo lol
How do I define parameters to include or not?
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\USER\Desktop\ZENESIS DEVELOPEMENT\PYTHON\ZENESIS\WARN SYSTEM [MONGO]\commands\warn.py", line 102, in remove_warn
test = r.find({}, {"guild": ctx.guild.id, "member": member.id}).sort({"warn", -1})
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\motor\metaprogramming.py", line 272, in return_clone
cursor_method(self.delegate, *args, **kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\cursor.py", line 726, in sort
keys = helpers._index_list(key_or_list, direction)
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\helpers.py", line 73, in _index_list
raise TypeError("if no direction is specified, "
TypeError: if no direction is specified, key_or_list must be an instance of list
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: if no direction is specified, key_or_list must be an instance of list
@maiden fable ^
Weird
i am even not getting why
Same
Breh
sry but i always take help from him whenever i get a unknown db error
Try seeing this
lemme check
lemme try this
just because of a curly brace i was getting that error
now i am getting ```AsyncIOMotorCursor(<pymongo.cursor.Cursor object at 0x0000026991699190>)
@maiden fable
need help
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\USER\Desktop\ZENESIS DEVELOPEMENT\PYTHON\ZENESIS\WARN SYSTEM [MONGO]\commands\warn.py", line 103, in remove_warn
fin = test["warn"]
TypeError: 'AsyncIOMotorCursor' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'AsyncIOMotorCursor' object is not subscriptable
i want to get the descended value from warn in my mongodb but how can i get that descended value now
Please don't ping random people for help. I know absolutely nothing about mongo. If you have a question about databases, post in #databases, not in this channel.
sry but i tried in that channel , no one was able to answer thats why i thought of asking in this
Hey can any one help me in testing of my bot?
What testing, and do you need any help with it?
i want to test ban and kick commands
nope
one of member is afk they not responding
I mean thats the best thing to do to test tbh
hi does anybody know how to make a footer for an embed? idk how and i'm kinda confused
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.
yee
U didn't call a function or something
wdym?
That happens when u didn't call a function in yr code
will it work ```py
test = r.find({"guild": ctx.guild.id, "member": member.id}).sort("warn", -1)
for x in test["warn"]:
print(x)
Idk, never used mongo
if this is motor, you'd need async for x in test:, where x becomes each individual document
ok lemme try
Ah, I think thTs the problem
i sent the relevant documentation in #databases
you should read it
In the discord API, what is a "partial" object? I wasn't able to find the definition anywhere.
anand im not able to login through my discord bot client is it put down for violating terms or something
It's an object a bot "can't" see. Like PartialMessage is a message sent in a guild the bot isn't the part of
Same with PartialEmoji. It's an emoji from a guild the bot isn't the part of
But what is its structure? What fields does it have etc.?
!d discord.PartialMessage
class discord.PartialMessage(*, channel, id)```
Represents a partial message to aid with working messages when only a message and channel ID are present.
There are two ways to construct this class. The first one is through the constructor itself, and the second is via [`TextChannel.get_partial_message()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.TextChannel.get_partial_message "discord.TextChannel.get_partial_message") or [`DMChannel.get_partial_message()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.DMChannel.get_partial_message "discord.DMChannel.get_partial_message").
Note that this class is trimmed down and has no rich attributes.
New in version 1.6...
I'm not talking about discord.py, just the API definition
afaik partials are just a way to still create the objects when the bot doesnt receive enough information
and they are a library only thing
Yea
No, they're not https://discord.com/developers/docs/resources/invite
guild? partial guild object
channel partial channel object
oh
Weird
then dont listen to me, I may have misread something
Tbh, I also didn't really understood the Partial objects, and I like to use the proper objects like discord.Message
I dont think you are really supposed to use them normally anyways, since they lack most important data the object should have. Unless you are doing something tricky, hacky or wacky
Indeed
can anyone help me with this
import os
import discord
import os
# load our local env so we dont have the token in public
from dotenv import load_dotenv
from discord.ext import commands
from discord.utils import get
from discord import FFmpegPCMAudio
from discord import TextChannel
from youtube_dl import YoutubeDL
load_dotenv()
client = commands.Bot(command_prefix='.') # prefix our commands with '.'
players = {}
@client.event # check if bot is ready
async def on_ready():
print('Bot online')
# command for bot to join the channel of the user, if the bot has already joined and is in a different channel, it will move to the channel the user is in
@client.command()
async def join(ctx):
channel = ctx.message.author.voice.channel
voice = get(client.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.move_to(channel)
else:
voice = await channel.connect()
# command to play sound from a youtube URL
@client.command()
async def play(ctx, url):
YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}
FFMPEG_OPTIONS = {
'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
voice = get(client.voice_clients, guild=ctx.guild)
if not voice.is_playing():
with YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
URL = info['url']
voice.play(FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))
voice.is_playing()
await ctx.send('Bot is playing')
# check if the bot is already playing
else:
await ctx.send("Bot is already playing")
return
# command to resume voice if it is paused
@client.command()
async def resume(ctx):
voice = get(client.voice_clients, guild=ctx.guild)
if not voice.is_playing():
voice.resume()
await ctx.send('Bot is resuming')
# command to pause voice if it is playing
@client.command()
async def pause(ctx):
voice = get(client.voice_clients, guild=ctx.guild)
if voice.is_playing():
voice.pause()
await ctx.send('Bot has been paused')
# command to stop voice
@client.command()
async def stop(ctx):
voice = get(client.voice_clients, guild=ctx.guild)
if voice.is_playing():
voice.stop()
await ctx.send('Stopping...')
# command to clear channel messages
@client.command()
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)
await ctx.send("Messages have been cleared")
nothing except.help works
raised an error: ExtensionFailed: Extension 'cogs.love' raised an error: OSError: cannot open resource```
does anyone know what is the cause of this?
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
running on local it's okay, when it's deployed it gets an error
!d DiscordUtils
No documentation found for the requested symbol.
I don't think so, it only sends images via bytesio
maybe open files from bytesio
but it runs on a normal local, no errors
is the module dislash safe?
i want to create context menus
so what are the dependencies if there are any
hello, can someone help, is discord.py only used for discord bots?
or you can do some basic tasks with it to
lets say just type some message i tell it to type, in some server or dm
oh it has to work with the bot?
what i meant is if discord.py can kind of do some tasks on my account,
ah, i see
what about logging in
i give it username or password or maybe my token and it logs me in, is that technically possible
Ya
aight, I'II try that stuff out
oh, not even that?
aight well lol guess i will find another project to work with, cause i dont think i will be able to make bots cause iam pretty new
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
gotcha, i didnt know that was again tos, thanks for the help tho
i think you said that about sending message not logging in, just for the record iam new to python and modules specificly so was just trying to learn
aight cya!
is it possible to use a for loop and look through all messages in a channel
lol against tos
oh lol
it was to check how many msgs u've sent in a channel
what is discordutils.music
music bot
Traceback (most recent call last):
File "F:\python project\webhookbot.py", line 1, in <module>
from discord_webhook import DiscordWebhook
ModuleNotFoundError: No module named 'discord_webhook'
Process finished with exit code 1
pls help me to eror cmd
any one who can help me with aiosqlite3
@rain bolt, looks like you posted a Discord webhook URL. Therefore, your message has been removed, and your webhook has been deleted. You can re-create it if you wish to. If you believe this was a mistake, please let us know.
my 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.pydis.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.
webhook = DiscordWebhook(url='', content='Sykhob ast \n @here')
response = webhook.execute()```
?
Traceback (most recent call last):
File "F:\python project\webhookbot.py", line 1, in <module>
from discord_webhook import DiscordWebhook
ModuleNotFoundError: No module named 'discord_webhook'
Process finished with exit code 1
eror
:||
tnx
pip install DiscordUtils
discord music
guys i have level system how to add to him role reward example: Every level up = role
i have on_guild_join event that changes voice channel name, in on guild remove im tryna get it too do that same thing but it doesnt change the channel name at all...
@bot.listen("on_guild_remove")
async def remove(guild):
voice = bot.get_channel(881797481694900225)
await voice.edit(name=f"Guilds: {len(bot.guilds)}")```
Any error?
nope
The Id is valid?
you need an instance of discord.VoiceChannel, you have it as vc so use .connect() method on it
await vc.connect()
ok
yh
that’s because you don’t have a error handler lmao
Can you print voice
how to call that codm now
If you mean command then, Like how you normally do it,
prefixplay url channel
and if you want it to tell you how much guilds it’s in, make a task loop.
ik that but how to call channel
hmmm
or just length it - 1
You can just pass id
not hard 🤷♂️
you can also do this
do that not working
Any error
ahh I didn't see, you are using name instead of id in utils.get
just typehint the channel argument
^
def send_typing(seconds=3):
def decorator(func):
@functools.wraps(func)
async def wrapper(*args, **kwargs):
args[0].bot.loop.create_task(asyncio.wait_for(args[0].typing(), timeout=seconds))
await func(*args, **kwargs)
return wrapper
return decorator
```seems that it did not trigger the typing?
sitll not working
typehint channel to discord.VoiceChannel as nubz said and then await channel.connect()
so i changed the code a bit
def send_typing(seconds=3):
def decorator(func):
@functools.wraps(func)
async def wrapper(*args, **kwargs):
with args[0].typing():
print("hi2")
await func(*args, **kwargs)
print("hi3")
print("hi")
return wrapper
return decorator
```hi3 and hi was never printed... probably the `await func(*args, **kwargs)` blocks the context manager?
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In emoji_id: Value "881503416436805642>'" is not snowflake.
How to get the emoji id out of a message
pls help🙏
Yes it is the func
Maybe yes, your func is still getting executed and waiting for returning
^
ohh
i see
i think i should create it as a task then
commands.Bot
It will still block tho (if you try getting the result there)
I have a list index of i which represents my level
how do I find all the other levels
I want to remove all the other roles on the user so his level roles dont stack
How to make bot reaction to its own message, and when you click on this reaction, it must do an event?
How can i get a id of an emote
out of a message
mensaje3 = await ctx.send('¿Con qué emote reacciono? Escribe `cancelar` para salir.')
eliminar.append(mensaje3)
message3 = await bot.wait_for('message', check=check)
eliminar.append(message3)
if message3.content.lower() == 'cancelar':
await borrar_msgs(eliminar)
await ctx.send('Comando cancelado.', delete_after=3)
return
else:
emoticono = f"{int(message3.content)}"
await mensaje_reaccion.add_reaction(emoticono)```
this error
File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In emoji_id: Value "881503416436805642>'" is not snowflake.
commands.Bot
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
hey bud
!yt
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
oh ya
@gloomy coral btw i need a bit help
in member.add_roles am i supposed to get the id or can directly use the name
@gloomy coral
^
You need the Role object
example will be better for me
role = member.guild.get_role(role_id)
await member.add_roles(role)```
only role id
Maybe an id will also be enough, but not sure
??
What?
is it possible with the name
You'd need to use discord.utils.get
like instead of id i will use its name
role = discord.utils.get(member.guild.roles, name='the name')
await member.add_roles(role)```
well it can be done thanks
is it possible to add buttons with discordpy lib?
yes, you can use v2
how to install v2?
pip install -U git+https://github.com/Rapptz/discord.py
mmh okay
@slate swan sry for ping but i have a question that if i ban a user so will it execute the on_member_remove event or i need to use on_member_ban
and if i use python3 -m pip install -U discord.py it installs wich version?
1.7.3
okay thx
I guess the latter, also just put your question here and don't ping anyone randomly
but does the discordpy doc supports the v2?
wdym by latter?
_ban
ok
both?
but doesnt it require the guild param
Change the docs url's stable to master and you'll find docs for 2.0
okay thx !
!d discord.on_member_ban
discord.on_member_ban(guild, user)```
Called when user gets banned from a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild").
This requires [`Intents.bans`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.bans "discord.Intents.bans") to be enabled.
guild and user
I think the first one is when member itself left or gets kicked
Also the latter one returns a user and guild object rather than member like in the former
last question ^^: is latest the same as master?
yeah, but user + guild is member
In events, you don't need to put the params yourself, dpy do that for you and you receive them
Yes
But I don't think _remove will trigger for ban if there's a separate event
yeah, the docs say when a member leaves a guild, doesnt mention about kicked/banned

What is occuring with discord.py?
What do I need to do for my bot to continue working?
dpy will work
ok thx
after modifying a slash command option type i have to wait upto an hour for those changes to apply correct?
!paste
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.pydis.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.
one last question, is then discord.py V.2 going to get out?
pun is not none
Ignoring exception in command warn:
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\USER\Desktop\ZENESIS DEVELOPEMENT\PYTHON\ZENESIS\WARN SYSTEM [MONGO]\commands\warn.py", line 108, in warn
punish = pool["punishment"]
TypeError: '_asyncio.Future' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: '_asyncio.Future' object is not subscriptable```
officially, no
pool = p.find_one({"guild": ctx.guild.id})
print(pool)```
i am getting the error at this line
you need to await it
officially?
p.find_one, that is
what does that means?
ooo yeah u r right
yes, the official repo is archived therefore cant release 2.0
that needs to be awaited as it is motor
but is there any "unofficial" repo?
many
the development has stopped but you can still install it from github
okok thx
discord.py have 3k forks
ofc there should be some
async def lvl_top(self,ctx,page=0):
db = sqlite3.connect("lvl.db")
curosor = db.cursor()
current = 1
index = 1
member_per_page = 3
embed = discord.Embed(title=f"{page}",description=f"")
msg = await ctx.send(embed=embed)
while True:
if current != page:
embed.title = f"{page}"
embed.description = f""
curosor.execute("SELECT member_id,exp, lvl FROM lvl WHERE guild_id = ? ORDER BY exp DESC LIMIT ? OFFSET ?", (ctx.guild.id,member_per_page,page,))
index = member_per_page*(current-1)
wynik = curosor.fetchall()
for entry in wynik:
index += 1
member_id = entry[0]
exp = entry[1]
member = ctx.guild.get_member(member_id)
embed.description += f"{index}) {member.mention} - {exp}\n"
await msg.edit(embed=embed)``` Whi it only reacts only for first command
and why in 1 page no one is but on next they are
<object Rush2618 at 0x001B561E0> can you help??
don't connect to the db every time a command in invoked
ok but can you help
i am not sure sorry
You don't have to make your own pages, you can paginate it in another way.
from discord.ext.buttons import Paginator
class Pag(Paginator):
async def teardown(self):
try:
await self.page.clear_reactions()
except discord.HTTPException:
pass
class SomeClass(commands.Cog):
@commands.command()
async def page_names(self, ctx, names:list):
pager = Pag(
timeout=3600, # how much it takes for the buttons to time out
entries=names, # the array that you want to be paginated
length=20, # how many items in a single page
prefix="",
suffix=""
)
await pager.start(ctx)
yes i know but it will add 5 emojis
i want to do it like this can you help?
Because if i will use paginator i will use it with ⬅️ and ➡️ emojis
2 of them are to go back and forward one by one, 2 of them are to go back and forward from the start to end, 1 is to stop the buttons.
It just gives easier use.
@commands.command(aliases=["gi","googleimages","image"])
async def googleimage(self, ctx, num:int,*imaged):
await ctx.send("This might take a few seconds")
q = " ".join(imaged)
start = 1
_search_params = {
'q': q,
'searchType': 'image',
'num': num,
'start': start,
'safe': 'medium',
'fileType': 'jpg',
'imgType': None,
'imgSize': None,
'imgDominantColor': None
}
gis.search(self,search_params=_search_params, path_to_dir='\images')
count = 1
dirrr = "\images"
for file in os.listdir(dirrr):
if file.endswith(".jpg"):
os.rename(f".\images\{file}",
f".\images\image{count}.jpg")
count += 1
for image in os.listdir('.\images'):
if image.startswith("image"):
await ctx.send(file=discord.File(f'\images\{image}'))```
This wont work
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/chad-the-discord-bot/cogs/info.py", line 244, in googleimage
gis.search(self,search_params=_search_params, path_to_dir='\images')
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/google_images_search/fetch_resize_save.py", line 125, in search
if not self._search_again:
AttributeError: 'Info' object has no attribute '_search_again'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Info' object has no attribute '_search_again'```
Where is gis defined?
from google_images_search import GoogleImagesSearch as gis
I'm not sure but I believe that this is a bug with the library you are using.
Try removing self from gis.search().
it shows error
!d discord.Server
No documentation found for the requested symbol.
class discord.Guild```
Represents a Discord guild.
This is referred to as a “server” in the official Discord UI.
`x == y` Checks if two guilds are equal.
`x != y` Checks if two guilds are not equal.
`hash(x)` Returns the guild’s hash.
`str(x)` Returns the guild’s name.
ok so let's try change it
member.guild not discord.Guild.
like that ?
And I suggest you don't put the id in a string.
Yes.
id is always an int
ok thanks
ok, thanks and let try
Guys, i want to make a leaderboard feature, which tells the top 3 active users of the server of the past 3 days, any idea how can i do that?
umm?
!pypi sorting if you want to sort them according to a certain system (like points or the economy) you can use this sorting package which will allow you to sort them descendingly, then you can get the top 3 of the list index [0:2].
ohhhhh, thanx man, i also wanted to know, where to record their number of messages?
Use a database.
I see, thanx
No problem.
async def lvl_top(self,ctx):
db = sqlite3.connect("lvl.db")
curosor = db.cursor()
page = 0
current = 1
index = 1
member_per_page = 3
emojis = ["⬅️","➡️"]
embed = discord.Embed(title=f"{current}",description=f"")
msg = await ctx.send(embed=embed)
await msg.add_reaction("⬅️")
await msg.add_reaction("➡️")
while True:
if current != page:
embed.title = f"{current}"
embed.description = f""
curosor.execute("SELECT member_id,exp, lvl FROM lvl WHERE guild_id = ? ORDER BY exp DESC LIMIT ? OFFSET ?", (ctx.guild.id,member_per_page,member_per_page*(current -1),))
index = member_per_page*(current-1)
wynik = curosor.fetchall()
for entry in wynik:
index += 1
member_id = entry[0]
exp = entry[1]
member = ctx.guild.get_member(member_id)
embed.description += f"{index}) {member.mention} - {exp}\n"
await msg.edit(embed=embed)
try:
reaction, user = await self.client.wait_for("reaction_add", check=lambda reaction, user: user == ctx.author and reaction.emoji in emojis, timeout=60.0)
except asyncio.TimeoutError:
return await msg.clear_reactions()
else:
if reaction.emoji == "➡️":
current += 1
elif reaction.emoji == "⬅️":
current -= 1
await msg.edit(embed=embed)``` How to do if next page is cleare (or on -) it will return and dont edit page??
How do i use asyncio to sleep for 3 days😅
await asyncio.sleep(3 * 24 * 60 * 60)
if reaction.emoji == "➡️":
current += 1
elif reaction.emoji == "⬅️":
if current < 0 or current-=1 < 0:
return
current -= 1
ohh, ok thanku
i will try
If your bot's uptime can be more than 3 days, else it'll reset with bot
I'm not sure how to check if the embed is empty tho.
oh, i see, thank you for telling me that
Is there anyway i can check the day of India using datetime module?
there is nothing as -=
itts for this buton ➡️
Is there anyway i can check the day of India using datetime module???
nvm ._.
Anyone can tell?
i meant cuz he was using some new syntax . weird joke
Now reaction is not working lol
@slate swan here is question
yeah mb, i did not see the context lol
i think so , you can use a api to check the time of each country in the world
I'm bad at this lmao. 
I see
why are you not using bot.wait_for ?
Yes, use the IST (GMT + 5:30) timezone aware datetime object
he is tho
Why not lol
check this
Oh ok
A ok but can you help me?
livelove please check what i sent its what ur trying to do
thenx
now here comes the big code
@bot.command()
async def cant(ctx):
timeout = 4
if ctx.message.author.id == 801474997238366209:
await ctx.send('type anything')
def check(m: discord.Message): # m = discord.Message.
return m.author.id == ctx.author.id and m.channel.id == ctx.channel.id
msg = await bot.wait_for(event = 'message', check = check, timeout=timeout)
lst = []
string = ''
try:
try:
lst.append(msg.content)
for i in lst:
string+=i
float(string)
await ctx.send('its a float / int')
except (ValueError , TypeError):
await ctx.send('not a int nor a float')
except asyncio.TimeoutError:
await ctx.send(f"**{ctx.author.mention}**, you didn't send any message that meets the check in this channel for {timeout} seconds..")
return
embed = discord.Embed(title=f"requested by {ctx.author}",description=f"\n{msg.content}\n")
await ctx.send(embed=embed)
``````discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TimeoutError:```
why doesnt it not work 
timeouterror:
what's after that
the timouterror wasnt catched altho i had it
@slate swan thats the error , notice in my msg = await bot.waitfor(etc)
in this link is no answer on me question
i had a timeout
import asyncio
import discord
from typing import Union
@bot.command(name="reactiontest")
async def reaction_test(ctx): # waiting for reactions (✅, ❌) here
await ctx.send(f"**{ctx.author}**, please react with :white_check_mark: or :x: on this message in 60 seconds")
def check(r: discord.Reaction, u: Union[discord.Member, discord.User]): # r = discord.Reaction, u = discord.Member or discord.User.
return u.id == ctx.author.id and r.message.channel.id == ctx.channel.id and \
str(r.emoji) in ["\U00002705", "\U0000274c"]
# checking author, channel and only having the check become True when detecting a ✅ or ❌
# else, it will timeout.
try:
# event = on_reaction_add without on_
reaction, user = await bot.wait_for(event = 'reaction_add', check = check, timeout = 60.0)
# reaction = discord.Reaction, user = discord.Member or discord.User.
except asyncio.TimeoutError:
# at this point, the check didn't become True.
await ctx.send(f"**{ctx.author}**, you didnt react with a ✅ or ❌ in 60 seconds.")
return
else:
# at this point, the check has become True and the wait_for has done its work, now we can do ours.
# here we are sending some text based on the reaction we detected.
# unicode for ✅ :
# https://emojipedia.org/emoji/✅/#:~:text=Codepoints
if str(reaction.emoji) == "\U00002705":
return await ctx.send(f"{ctx.author} reacted with a ✅")
# or we could also add a role here, like so
# role = await ctx.guild.get_role(ROLE_ID)
# await ctx.author.add_roles(role)
# unicode for ❌ :
# https://emojipedia.org/emoji/❌/#:~:text=Codepoints
if str(reaction.emoji) == "\U0000274c":
return await ctx.send(f"{ctx.author} reacted with a ❌")```
look at this
maybe I'm dumb, but
But me question is How to do if next page is cleare (or on -) it will return and dont edit page??
good point , i'll check that rn
i have another problem
How do i use a loop to keep checking the date after one hour and if the date is divisible by 3, it should send a message to the server(i know about which channel and stuff)
@slate swan
!d discord.ext.tasks.Loop
class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.
The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
i'm really tired , cant even fix my own error
i know about loops, but i am confused how to use them
a ok
why are you passing in event as a kwarg tho
@tasks.loop(hours=1)
async def check_date(self):
. . . .
i am not using cogs
then remove the self
it doesn’t matter since it’s not positional only iirc
ND HOW DO I ACTIVATE THE LOOP?
calm down
ok sir
#help-croissant im stuck
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User "discord.User").
`x == y` Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User "discord.User") instances too.
`x != y` Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User "discord.User") instances too.
`hash(x)` Returns the member’s hash.
`str(x)` Returns the member’s name with the discriminator.
I have some more things.......
How do I check if the today's date is divisible by 3?
I have the function to get the current date, but can i check if it is divisible by 3?
use the modulus operator
How to make a global / command. Like MEE6 or Groovy :( rip
How to get a list of all category channels?
Guys which kwarg is used to count the members in the guild
Hey so i created a ticket system and i don't know how to set channel permission that not everyone will see the channel, just the message author and the staff
Property*
!d discord.Guild.member_count
member_count```
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.members "discord.Intents.members") to be specified.
Thanks
members```
A list of members that belong to this guild.
It will count the bots too right?
!d discord.Guild.create_text_channel use the overwrites kwarg
await create_text_channel(name, *, overwrites=None, category=None, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/stable/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/stable/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/stable/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/stable/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/stable/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
Mhm
!d discord.Guild.member_count
member_count```
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.members "discord.Intents.members") to be specified.
Will it count the bots too, cause I don't think that this method will @maiden fable
It will bro
Wdym?
@maiden fable
It will count
Ooh I see
hi guys how can i add button in bot activity with link ?
U can't
Discord Problem
Lol
really ?
Guys, how do i write the names of people in a txt file, whenever they message
only the names
open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)```
Open *file* and return a corresponding [file object](https://docs.python.org/3.10/glossary.html#term-file-object). If the file cannot be opened, an [`OSError`](https://docs.python.org/3.10/library/exceptions.html#OSError "OSError") is raised. See [Reading and Writing Files](https://docs.python.org/3.10/tutorial/inputoutput.html#tut-files) for more examples of how to use this function.
*file* is a [path-like object](https://docs.python.org/3.10/glossary.html#term-path-like-object) giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless *closefd* is set to `False`.)
!d print
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)```
Print *objects* to the text stream *file*, separated by *sep* and followed by *end*. *sep*, *end*, *file*, and *flush*, if present, must be given as keyword arguments.
All non-keyword arguments are converted to strings like [`str()`](https://docs.python.org/3.10/library/stdtypes.html#str "str") does and written to the stream, separated by *sep* and followed by *end*. Both *sep* and *end* must be strings; they can also be `None`, which means to use the default values. If no *objects* are given, [`print()`](https://docs.python.org/3.10/library/functions.html#print "print") will just write *end*.
The *file* argument must be an object with a `write(string)` method; if it is not present or `None`, [`sys.stdout`](https://docs.python.org/3.10/library/sys.html#sys.stdout "sys.stdout") will be used. Since printed arguments are converted to text strings, [`print()`](https://docs.python.org/3.10/library/functions.html#print "print") cannot be used with binary mode file objects. For these, use `file.write(...)` instead.
Your code
add the number of messages everytime they message?
Like:
Black goku = 0 messages
again i message
it says 1
then 2, 3,4 and so on
counter = 0
with open("leaderboard.txt", "r+") as file1:
for lines in y:
if lines.strip("\n") == str(message.author.display_name):
counter += 1
file1.writelines(f"{str(message.author.id)}\n")
do you want to save the message count per member?
Then you will need to use a dictionary
@bot.command()
async def cant(ctx):
timeout = 4
if ctx.message.author.id == 730644317894344734:
await ctx.send('type anything')
def check(m: discord.Message): # m = discord.Message.
return m.author.id == ctx.author.id and m.channel.id == ctx.channel.id
lst = []
string = ''
msg = await bot.wait_for(event = 'message', check = check, timeout=timeout)
try:
try:
lst.append(msg.content)
for i in lst:
string+=i
float(string)
await ctx.send('its a float / int')
embed = discord.Embed(title=f"requested by {ctx.author}",description=f"\n{msg.content}\n")
return await ctx.send(embed=embed)
except (ValueError , TypeError):
await ctx.send('not a int nor a float')
embed = discord.Embed(title=f"requested by {ctx.author}",description=f"\n{msg.content}\n")
return await ctx.send(embed=embed)
except (TimeoutError,asyncio.TimeoutError,discord.ext.commands.errors.CommandInvokeError):
await ctx.send(f"**{ctx.author.mention}**, you didn't send any message that meets the check in this channel for {timeout} seconds..")
return```
```py
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TimeoutError:```
explain why
regenerate the token is what u should do
pass the url
Someone knows why is this doesn't works?
bruh
i didnt mean it in a bad way
u cant react with embed
its like this
embed.set_image(url=X)
wait lemme see
the embed works but it don't delete the channel when i click the reaction
How did u do this
just do client.channel.delete ?
lmao
but where
DM FOR BEST MUSIC BOT SAFE H BC , please read the docs
not works
read the docs and find it , not sure what was the name for it
from collections import defaultdict
message_count = defaultdict(int)
@bot.listen()
async def on_message(message):
message_count[message.author.id] += 1
with open("leaderboard.txt", "a+") as file1:
... # do whatever you want```
!d collections.defaultdict
class collections.defaultdict(default_factory=None, /[, ...])```
Return a new dictionary-like object. [`defaultdict`](https://docs.python.org/3.10/library/collections.html#collections.defaultdict "collections.defaultdict") is a subclass of the built-in [`dict`](https://docs.python.org/3.10/library/stdtypes.html#dict "dict") class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the [`dict`](https://docs.python.org/3.10/library/stdtypes.html#dict "dict") class and is not documented here.
The first argument provides the initial value for the [`default_factory`](https://docs.python.org/3.10/library/collections.html#collections.defaultdict.default_factory "collections.defaultdict.default_factory") attribute; it defaults to `None`. All remaining arguments are treated the same as if they were passed to the [`dict`](https://docs.python.org/3.10/library/stdtypes.html#dict "dict") constructor, including keyword arguments.
[`defaultdict`](https://docs.python.org/3.10/library/collections.html#collections.defaultdict "collections.defaultdict") objects support the following method in addition to the standard [`dict`](https://docs.python.org/3.10/library/stdtypes.html#dict "dict") operations:
Oh, u wrote all that for me....., Lord Rush
thanku tho
very much thanku
😄
;-;
How to see how many servers that my bot are in (i wanna set it on bot status) also how to see the server list
i'd suggest using a database
@slate swan
if message.content.startswith('^botservers'):
await client.send_message(message.channel, "I'm in " + len(client.servers) + " servers!")``` example , you work with it
how about how to see what servers that my bot are in
Is there anyway?
Like import server list to txt file or in console
like there names and stuff ? , i really dont think so
yeah
also its this
if message.content.startswith('^botservers'):
await message.channel.send("I'm in " + str(len(client.guilds)) + " servers!")``` my bad
bot
oh
Just realized that it's bot command lol
@bot.event
async def on_ready():
print('logged in')
await bot.change_presence(activity=discord.Activity(
type=discord.ActivityType.playing, name=f"playing {str(len(bot.guilds))} servers"))``` i assume this would work
I want the bot event one
and just can enter admins, one role and a person that have reacted to a message
oh yes
hm hm , did u consider reading the docs
@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Streaming(name='Minecraft' , url="http://www.twitch.tv/accountname"))
``` my current one
make a channels pass the parameters perms= , was something like that
they are a bit confusing 
Idk where it is
Trying
search for it in the docs , i really forgot
lemme see 1 sec
Working fine ty!
i think py await create_guild(name, region=None, icon=None, *, code=None)
your welcome
wait wrong one
text channel right ?
yeah its that
channel = await guild.create_text_channel('pass the name here')
to change perms u could use this
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
guild.me: discord.PermissionOverwrite(read_messages=True)
}
channel = await guild.create_text_channel('secret', overwrites=overwrites)```
its a dict
thanks
np
😫 sheesh
Yeah
NVM.
Hey people,
Can anyone willingly teach me discord.py? I am really keen to learn, and hopefully I'll be a very good student. I can invest all my time, i just need a live teacher to help and teach me.
is it possible for my bot to manage the channel permissions of the channel it creates?
Im trying to make it so that anyone can upload attachments
Yes
bruh
look at tutorials
Hey is there any discord bot developer who would like to be involved in a custom bot project for a partnered server
99% sure you dont get a live teacher
from here at least




lmk if there is any errors

