#discord-bots
1 messages · Page 645 of 1
.
I've already done that bro
Bro......nvm
I've tried literally all the common fixes I'd usually try before coming here for help
I don't know why you're getting mad, you chose to come in here and try and help while robin and AM were, you're blaming me for getting toxic now when no one got toxic.
It's not needed
I'll get the code one sec
I'll leave then baiii
that's probably the oddest thing i've seen all day today
I've had something weirder than this occur surprisingly
you mustn't be having a good day haha
Honestly, I'm a little stumped, because usually when you have missing access, it's that it dosen't have access to the channel
I am too
I feel like this might be cause for a bug report
Starting to think it's genuinely a bug on their end
async def on_member_join(member):
guild = ctx.message.guild
await guild.create_text_channel('cool-channel')
how would I get this to work bc ctx isn't defined
..
you can get guild from member.guild
on_membe_join takes only member arg
alr ty
anyone?
"This isn't working" isn't very helpful. We'll need a few things to fully understand & diagnose the problem:
- What do you want it to do?
- What does it do?
- Are there errors in console?
@worthy wagon Maybe check your channel ID again? Idk at this point
Yeah, usually it's just something silly like forgetting perms, but I'm completely stumped
best bet would be to check the ID and give it a day
i want it to choose any the number of random choices from the list as much as the user wants and the number of times the user wants it
that shud be done
Off the top of my head you're running the while loop for every, you never modify h or p
Also this is going to get you rate limited fast and most likely API banned
@worthy wagon oheyo, try using exceptions in your code
We know what the problem is
Well actually no we don't
but we kinda do if that makes any sense
we know that we get a 403 forbidden error, except the bot definitely has access to the channel, we've checked everything
so we're quite stumped
*403
yeah sorry
They deleted the error message for some reason, but it said "Missing Access" as well
What does it not have acces to
the channel being fetched
Good luck
Lol
@civic fractal you speak spanish?
un poco
ok
Could you help me with something please
I have time on hold and no Helper answers me
Hi if i want my bot to mention who is joining my server on the terminal what code is it?
like while the code is running
@bot.event
async def on_member_join(member):
channel = await bot.fetch_channel(915769665140170792)
await channel.send(f'Welcome to server **{member.mention}**.')
to let the bot mention a member is it {member.mention}?
like does this seem right
myEmbed = discord.Embed(title = f"Welcome {member.mention}",
@lethal bloom
The mention won't work in the title
title no
ok well that sucks
description
then how to do it..
ok then
p+=1?
name user? :D
also how to divide an embed into pages? ```py
@client.command()
@commands.has_permissions(administrator=True)
async def inrole(ctx, r_id: int):
g = ctx.guild
r = nextcord.utils.get(g.roles, id=r_id)
names = [m.name for m in r.members]
try:
embed=nextcord.Embed(title=f"Displaying members with that role", description='\n'.join(names))
await ctx.send(embed=embed)
except:
await ctx.send("The embed size is too large!")```i read some docs but didnt quite understand it
class MyEmbedDescriptionPageSource(menus.ListPageSource):
def __init__(self, data):
super().__init__(data, per_page=6)
async def format_page(self, menu, entries):
g=self.guild
r = nextcord.utils.get(g.roles, id=r_id)
names = [m.name for m in r.members]
embed = Embed(title="Members in that role", description="\n".join(names))
embed.set_footer(text=f'Page {menu.current_page + 1}/{self.get_max_pages()}')
return embed
@bot.command()
async def button_embed_description(ctx, r_id:int):
data = [f'Description for members #{num}' for num in range(1, 51)]
pages = menus.ButtonMenuPages(
source=MyEmbedDescriptionPageSource(data),
disable_buttons_after=True,
)
await pages.start(ctx)```?
yess
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 168, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\admin\Downloads\ROG.py", line 1378, in inrole
await pages.start(ctx)
File "C:\Python310\lib\site-packages\nextcord\ext\menus\menu_pages.py", line 102, in start
await super().start(ctx, channel=channel, wait=wait)
File "C:\Python310\lib\site-packages\nextcord\ext\menus\menus.py", line 593, in start
self.message = msg = await self.send_initial_message(ctx, channel)
File "C:\Python310\lib\site-packages\nextcord\ext\menus\menu_pages.py", line 95, in send_initial_message
kwargs = await self._get_kwargs_from_page(page)
File "C:\Python310\lib\site-packages\nextcord\ext\menus\menu_pages.py", line 72, in _get_kwargs_from_page
value: PageFormatType = await nextcord.utils.maybe_coroutine(self._source.format_page, self, page)
File "C:\Python310\lib\site-packages\nextcord\utils.py", line 514, in maybe_coroutine
return await value
File "c:\Users\admin\Downloads\ROG.py", line 1363, in format_page
names = [m.name for m in r.members]
AttributeError: 'NoneType' object has no attribute 'members'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\nextcord\client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "c:\Users\admin\Downloads\ROG.py", line 658, in on_command_error
raise error
File "C:\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 995, in invoke
await ctx.command.invoke(ctx)
File "C:\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 895, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 177, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'members'```
isnt showing on my embed?
send ur code
async def on_member_join(member):
guild = client.get_guild(730651046459998218)
channel = guild.get_channel(885464532959526913)
myEmbed = discord.Embed(title = f"Welcome",
description= f"Welcome {member.mention}, You are member {guild.member_count}. \n Enjoy your stay here and dont forget to read the await [#904279966693355550](/guild/267624335836053506/channel/904279966693355550/)", color=0x0ff00)
await channel.send(embed=myEmbed)
role = guild.get_role(832120561848156180)
await member.add_roles(role)```
error?
Nope just isnt appearing on my embed
role=guild.get_role is wrong ig
use utils
Nope it works fine
officially made the funny
nvm it works now just had to restart the bot
bruh
u didnt restart the bot?
wow
wao
Was this fixed?
O can I see the code?
sure
class MyEmbedDescriptionPageSource(menus.ListPageSource):
def __init__(self, data):
super().__init__(data, per_page=6)
async def format_page(self, menu, r_id):
g=client.get_guild(855423177324363816)
r = g.get_role(r_id)
names = [m.name for m in r.members]
embed = Embed(title="Members in that role", description="\n".join(names))
embed.set_footer(text=f'Page {menu.current_page + 1}/{self.get_max_pages()}')
return embed
@client.command()
@commands.has_permissions(administrator=True)
async def inrole(ctx, r_id:int):
g=client.get_guild(855423177324363816)
r = g.get_role(r_id)
names = [m.name for m in r.members]
pages = menus.ButtonMenuPages(
source=MyEmbedDescriptionPageSource(names),
disable_buttons_after=True,
)
await pages.start(ctx)```
enhanced a bit
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 168, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\admin\Downloads\ROG.py", line 1381, in inrole
await pages.start(ctx)
File "C:\Python310\lib\site-packages\nextcord\ext\menus\menu_pages.py", line 102, in start
await super().start(ctx, channel=channel, wait=wait)
File "C:\Python310\lib\site-packages\nextcord\ext\menus\menus.py", line 593, in start
self.message = msg = await self.send_initial_message(ctx, channel)
File "C:\Python310\lib\site-packages\nextcord\ext\menus\menu_pages.py", line 95, in send_initial_message
kwargs = await self._get_kwargs_from_page(page)
File "C:\Python310\lib\site-packages\nextcord\ext\menus\menu_pages.py", line 72, in _get_kwargs_from_page
value: PageFormatType = await nextcord.utils.maybe_coroutine(self._source.format_page, self, page)
File "C:\Python310\lib\site-packages\nextcord\utils.py", line 514, in maybe_coroutine
return await value
File "c:\Users\admin\Downloads\ROG.py", line 1362, in format_page
r = g.get_role(r_id)
File "C:\Python310\lib\site-packages\nextcord\guild.py", line 805, in get_role
return self._roles.get(role_id)
TypeError: unhashable type: 'list'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\nextcord\client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "c:\Users\admin\Downloads\ROG.py", line 658, in on_command_error
raise error
File "C:\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 995, in invoke
await ctx.command.invoke(ctx)
File "C:\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 895, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 177, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unhashable type: 'list'```
new error with tht code
Seems like u r passing a list to r_id
i gave u thee code see
Can I see how u r invoking the command?
-inrole ()
removee the () with the role id
one sec
887186511555088435
role id...
nvm fixed it
@maiden fable hey
how to get role name by id?
!d discord.utils.get
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
Hi
how will i get the name by this tho.. i can get the role..
modify a little what you gave me, now only the invitation will come out.
How do I add a text next to the link?
get(guild.roles, name="")
send(f"{invite} text")
.. i want to geet a role name by its id
ok
Ah my bad
Or str(role)
The name of the role.
def __init__(self, data):
super().__init__(data, per_page=20)
async def format_page(self, menu, names, r):
embed = Embed(title=f"Members in that {r.name}", description="\n".join(names))
embed.set_footer(text=f'Page {menu.current_page + 1}/{self.get_max_pages()}')
return embed
@client.command()
@commands.has_permissions(administrator=True)
async def inrole(ctx, r_id:int):
print(r_id)
g=client.get_guild(855423177324363816)
r = g.get_role(r_id)
names = [f"{m.name}#{m.discriminator}" for m in r.members]
pages = menus.ButtonMenuPages(
source=MyEmbedDescriptionPageSource(names),
disable_buttons_after=True,
)
await pages.start(ctx)```
r = g.get_role(r_id)
this is my role var
r.name then
send(f"{invite} | {member.mention}")
it does not work
Use ``please
Mhm
async def on_member_join(member):
guild = client.get_guild(730651046459998218)
channel = await client.fetch_channel(885464532959526913)
description=(f"Welcome {member.mention}, You are member {guild.member_count}. \n Please enjoy your stay here and dont forget to read the await [#904279966693355550](/guild/267624335836053506/channel/904279966693355550/)"),
await channel.send(f'Welcome to server **{member.mention}**.')
role = guild.get_role(832120561848156180)
await member.add_roles(role)
``` is this the right code to show who joins ur server in ur code editor on a terminal?
can any1 help?
@maiden fable
Should work
Sorry was watching yt
ok
Welp gotta reinstall Spotify ;-;
What's the error?
ctx.author.mention
ok
Hunter do you ever sleep?
Ok sure
I have deleted all of my bot's code because of the if statements
lol
oh
nice bud
lol
i didnt code much, if you want, though, i could send you some of my bot's code in dm (after the changes)
Yea I woke up at 10 today after sleeping at 2:30 or something
I don't know much about python but a friend of mine does
you slept bout 7.5h?
@maiden fable work 👍
Tbh I slept till late sadly
Cool! :D
lucky I slept only 6h
@bot.command()
async def brackets(ctx,p:int):
while 0!=p:
a = (random.sample(my_list, k=2))
b=a[0]
s=a[1]
await ctx.send(f"{b} vs {s}")
p=p+1``` this keeps sending it
even if i giv the p as 2
if p is 0 or greater that while will never exit
Wait nvm, 0 is always unequal to p so the statement is always True
then how fo i write it..
while 0=p:
?
It's checking if p isn't equal to 0 which is gonna happen literally everytime
@prisma spoke
while p==0
You need this (:
it will run until p is 0
@slate swan 's answer was correcct..
tbh we are just guessing what you want to do
but now ```py
my_list = [k for k in users]
@bot.command()
async def brackets(ctx,p:int):
while 0!=p:
a = (random.sample(my_list, k=2))
b=a[0]
s=a[1]
await ctx.send(f"{b} vs {s}")
p-=1``` iwant like any of the elementsof the 2nd choice shudnt be equal to the 1st one
now how to do that
2
user ids..
how many are there in total
how many are there what?
6
itertools.pairwise(iterable)```
Return successive overlapping pairs taken from the input *iterable*.
The number of 2-tuples in the output iterator will be one fewer than the number of inputs. It will be empty if the input iterable has fewer than two values.
Roughly equivalent to:
```py
def pairwise(iterable):
# pairwise('ABCDEFG') --> AB BC CD DE EF FG
a, b = tee(iterable)
next(b, None)
return zip(a, b)
```...
huh? whats this
it will make sublists of the list each containing 2 elements
!e
from itertools import pairwise
ids = map(str, [1,2,3,4,5,6])
print(list(pairwise(ids)))```
@sullen shoal :white_check_mark: Your eval job has completed with return code 0.
[('1', '2'), ('2', '3'), ('3', '4'), ('4', '5'), ('5', '6')]
https://www.geeksforgeeks.org/break-list-chunks-size-n-python/
could try those as well
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
!d more_itertools.chunked
more_itertools.chunked(iterable, n, strict=False)```
Break *iterable* into lists of length *n*:
```py
>>> list(chunked([1, 2, 3, 4, 5, 6], 3))
[[1, 2, 3], [4, 5, 6]]
``` By the default, the last yielded list will have fewer than *n* elements if the length of *iterable* is not divisible by *n*:
```py
>>> list(chunked([1, 2, 3, 4, 5, 6, 7, 8], 3))
[[1, 2, 3], [4, 5, 6], [7, 8]]
``` To use a fill-in value instead, see the [`grouper()`](https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.grouper "more_itertools.grouper") recipe...
is it built-in module
no but its a simple install with pip install more-itertools
oh
yep i also wanna be a professional json engineer
hes not a json engineer..
😳 helo
he is one of the devs of nc
ik
hi
un expected indent
um ye
not copied
its copied
if u wud tell me u dont know python i wud have helped u but u told uk python.. and u didnt copy the code.. if uk python thn u must know what indent is
aanyways its an indentation error
hi guys
im learning....
how can we make modmail bot?
its an indentation error
try it and see
i finally made tictactoe
ik that...
bot\
do i -1 or tab 1
wat
yes.. so make that in line
modmail should be easy if you made tictactoe
ur indents are all wrong
oh
see wait
fixed it!
Hey @hazy agate!
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:
bruh
player1 = ""
player2 = ""
turn = ""
gameOver = True
board = []
winningConditions = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
]
@client.command()
async def tictactoe(ctx, p1: discord.Member, p2: discord.Member):
global count
global player1
global player2
global turn
global gameOver
if gameOver:
global board
board = ["⬜", "⬜", "⬜",
"⬜", "⬜", "⬜",
"⬜", "⬜", "⬜"]
turn = ""
gameOver = False
count = 0
player1 = p1
player2 = p2
# print the board
line = ""
for x in range(len(board)):
if x == 2 or x == 5 or x == 8:
line += " " + board[x]
await ctx.send(line)
line = ""
else:
line += " " + board[x]player1 = ""
player2 = ""
turn = ""
gameOver = True
board = []
winningConditions = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
]
@client.command()
async def tictactoe(ctx, p1: discord.Member, p2: discord.Member):
global count
global player1
global player2
global turn
global gameOver
if gameOver:
global board
board = ["⬜", "⬜", "⬜",
"⬜", "⬜", "⬜",
"⬜", "⬜", "⬜"]
turn = ""
gameOver = False
count = 0
player1 = p1
player2 = p2
# print the board
line = ""
for x in range(len(board)):
if x == 2 or x == 5 or x == 8:
line += " " + board[x]
await ctx.send(line)
line = ""
else:
line += " " + board[x]
my commanmd
determine who goes first
num = random.randint(1, 2)
if num == 1:
turn = player1
await ctx.send("It is <@" + str(player1.id) + ">'s turn.")
elif num == 2:
turn = player2
await ctx.send("It is <@" + str(player2.id) + ">'s turn.")
else:
await ctx.send("A game is already in progress! Finish it before starting a new one.")
@client.command()
async def place(ctx, pos: int):
global turn
global player1
global player2
global board
global count
global gameOver
if not gameOver:
mark = ""
if turn == ctx.author:
if turn == player1:
mark = "🇽"
elif turn == player2:
mark = "🅾️"
if 0 < pos < 10 and board[pos - 1] == "⬜" :
board[pos - 1] = mark
count += 1
# print the board
line = ""
for x in range(len(board)):
if x == 2 or x == 5 or x == 8:
line += " " + board[x]
await ctx.send(line)
line = ""
else:
line += " " + board[x]
checkWinner(winningConditions, mark)
print(count)
if gameOver == True:
await ctx.send(mark + " wins!")
elif count >= 9:
gameOver = True
await ctx.send("It's a tie!")
# switch turns
if turn == player1:
turn = player2
elif turn == player2:
turn = player1
else:
await ctx.send("Be sure to choose an integer between 1 and 9 (inclusive) and an unmarked tile.")
else:
await ctx.send("It is not your turn.")
else:
await ctx.send("Please start a new game using the !tictactoe command.")
def checkWinner(winningConditions, mark):
global gameOver
for condition in winningConditions:
if board[condition[0]] == mark and board[condition[1]] == mark and board[condition[2]] == mark:
gameOver = True
@tictactoe.error
async def tictactoe_error(ctx, error):
print(error)
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("Please mention 2 players for this command.")
elif isinstance(error, commands.BadArgument):
await ctx.send("Please make sure to mention/ping players (ie. @signal grotto).")
@place.error
async def place_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("Please enter a position you would like to mark.")
elif isinstance(error, commands.BadArgument):
await ctx.send("Please make sure to enter an integer.")
!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.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
!bot
Bot informational commands.
!u r bot
Could not convert "user_or_message" into Member, User, or Message.
Message "r" not found.
!user [user_or_message]
Can also use: member_info, member, u, user_info
Returns info about a user.
uf
freecodecamp's outdated tutorial ,-,
replit is so gud
ik but im learning from other websites to
not good for comp coding
bruh i have usaco in 10 days :((((
yea
replit is shit
it isnt
vs code >repl
notepad > vs code, boomer advice
my_list = [k for k in users]
@bot.command()
async def brackets(ctx,p:int):
while 0!=p:
a = (list(pairwise(my_list)))
await ctx.send(a)
p-=1``` i want it like any 2 random ints shud be displayed in a particular format
word doc> notepad>vs code
like choice1 vs choice2
idk what youre talking about
who
u
i mean i want the choices to be displayed like this:-
choice3here vs choice4here
like that
https://www.w3schools.com/python/ref_string_format.asp
try the formatting types
but i also use pycharm
mhh
how will tht help here?
!discord welcome
???
bruh
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
bruh
how will .format help?
idk how to explain more than that. you have to use your brain
explain 
my_list = [k for k in users]
@bot.command()
async def brackets(ctx,p:int):
while 0!=p:
a = (list(pairwise(my_list)))
await ctx.send(a)
p-=1``` @sullen shoal
this gave all values from the list
okay ¯\_(ツ)_/¯
this didnt rand.choice..
shuffle the list then
how to shuffle?
!d random.shuffle
random.shuffle(x[, random])```
Shuffle the sequence *x* in place.
The optional argument *random* is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function [`random()`](https://docs.python.org/3/library/random.html#random.random "random.random").
To shuffle an immutable sequence and return a new shuffled list, use `sample(x, k=len(x))` instead.
Note that even for small `len(x)`, the total number of permutations of *x* can quickly grow larger than the period of most random number generators. This implies that most permutations of a long sequence can never be generated. For example, a sequence of length 2080 is the largest that can fit within the period of the Mersenne Twister random number generator.
Deprecated since version 3.9, will be removed in version 3.11: The optional parameter *random*.
!e
from random import shuffle
foo = [1,2,3,4,5,6,7,8]
shuffle(foo)
print(foo)
@sullen shoal :white_check_mark: Your eval job has completed with return code 0.
[3, 2, 4, 8, 5, 1, 6, 7]
this ```py
my_list = [k for k in users]
@bot.command()
async def brackets(ctx,p:int):
while 0!=p:
a=shuffle(my_list)
await ctx.send(a)
p-=1```?
it wudnt print it twice?
shuffle doesn't return the list instead it replaces the orignal list
then shuffle doesnt answer my question..
im not helping with this more, this is basic python and and im not here to teach python
did u even get my question?
its not.. tbh..
it is basic
u didnt even get my question wow
i did get your question and provided all the stuff you need for it. i will not spoonfeed
say whats my question..
you want to shuffle the list, make sublists of it each containing 2 items then pretty print the list
i dont wanna shuffle the list
then wdym by that
get a random item from the list? that wasnt in your question or it wasn't clearly said
u again said shuffle wud replace the list
what do you want
choose random items from the list then make pairs of 2 then pretty print yes
isnt that basically shuffling the list?
shuffling replaces the list u said..
replaces with a new one..
so what
nd u also didnt tell that how to make pairs of 2

thats where the basics of python come to play
>>> import random
>>> import itertools
>>> foo = list(range(0, 10))
>>> random.shuffle(foo)
>>> list(itertools.pairwise(foo))
[(6, 5), (5, 0), (0, 2), (2, 8), (8, 9), (9, 3), (3, 1), (1, 4), (4, 7)]
>>>
Shuffle the list then make pairs, he basically already told you how
And now he spoonfeed you 😔🖐️
bro i cant control myself, its too painful
True 😔
u never told range
bruh
it wasnt even the question, they already had a list
ik it was in rand.choice but not itertools
i used range to create the list to give the example
He used itertools to pair the items
!d discord.User.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**.
or discord.Member.send
no i have my minimal help command in a class
so what
class MyNewHelp(commands.MinimalHelpCommand):
async def send_pages(self):
destination = self.get_destination()
for page in self.paginator.pages:
emby = discord.Embed(description=page)
await destination.send(embed=emby)
async def on_help_command_error(error):
await destination.send("We had an error. Try running the command again.")```
:troll:
Must've been another class then
!d discord.ext.commands.HelpCommand.context
The context that invoked this help formatter. This is generally set after the help command assigned, command_callback(), has been called.
Yeah that
Minimal one is subclass of this one
subclass help command = pog
hello
....dp....
pp
oh no
Y'all dirty minded 😔🖐️
😳
python programming
I-i knew that 😎
wtf

I enter and see this lmao
can I get a docs for using pagination
python programming
really funny
smh
I also like d's
wanna see my d?
Pretty sure you're the one who's supposed to make his own paginator, it's not builtin
Hey @velvet tinsel!
It looks like you tried to attach file type(s) that we do not allow (.jfif). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
f
my d ;-;
i made my paginator once and now i can copy paste it anywhere i want ez life
I'd like to express my deepest condolences for anyone who has had the misfortune of writing:
- a paginator
- a scheduler
Use DiscordUtils, its an easier way
gib source /j
whats a paginator
A scheduler, what's that?
embeds which change on reaction
oh
sweet
thats easy
interaction one or context
@sullen shoal i dont need range..
a =random.shuffle(my_list)
b = list(itertools.pairwise(a))
await ctx.send(a)
await ctx.send(b)```
you're different
I'm different?
idk
I always thought I was the same with other people?
everyone is
then why do people say "average"?
so.. to make a paginator I need a check function, reactions and event to wait for reaction?
dunno
yes
and then edit it
bruh plz
buttons are easier to manage
yay
my paginator is just around 150 lines, it was ez
by nature nobody can be average
the edit part it hardest one I guess
challenge accepted
u r above average
challenge?.....
I reckon I can do it in 50 lines 
imma use exec and boom one liner
I think you will do it in 1 line smh
nah one is just painful
!OT
Off-topic channels
There are three off-topic channels:
• #ot2-never-nester’s-nightmare
• #ot1-perplexing-regexing
• #ot0-psvm’s-eternal-disapproval
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
..
it isnt offtopic tbh
Mine's 71 😎
nice
imagine flexing a paginator thats 71 lines, mines 50 😨
https://github.com/m-y-x-i/simple-disnake-discord-bot/blob/main/utils/paginator.py
should work fine if discord.py 2.0
maybe
@bot.command()
async def brackets(ctx,p:int):
while 0!=p:
a =random.shuffle(my_list)
b = list(itertools.pairwise(a))
await ctx.send(a)
await ctx.send(b)
p-=1```
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'NoneType' object is not iterable
Your list is empty
nop
Yep
nice
a is None
huh? why?
but its not empty
As you've already been told, random.shuffle does not return the list, but replaces it
So assigning it to a variable will basically be assigning that variable None
and i am sending the replaced list
oof
then how to assign a var to it
Paginators are weird af
i have no clue what they are lol
In your opinion
not a opinion /j
it was even more weird, now its easy asf
Paginators are relatively easy
All they do is index a list of items and edit the message with the current item
And the buttons simply increase or decrease the index
those tasks are hard
oh those, thats what they are! i done something similar a while back for an audit log command
Mhm, they're extremely easy
indeed
actually 45~ lines my bad (for my help command)
Yours only has 3 buttons that's why 😔🖐️
yes
instead of making multiple paginators, i just added something that would help me turn off and on some buttons if i dont need
Nice
I don't even understand this kind of code..
💀
You give it a list of embeds, ctx, and then use the .start method
Me who uses a library lmao
Nice
paginator = EmbedPaginator(inter, doc_embeds)
await paginator.start()
``` doc_embed != a list of embeds?
?
It is
But sometimes it's just one embed
So there's no need to apply the paginator
visible confusion
How to make a bot that will create channels and manage permission of that channel?
heyyy
im trying to send images before texts
await channel.send(f"{member.mention} Welcome to our server. Check out {rules.mention} and {roles.mention}", file = file)
but i can't
send the image first then send the message
how to get the number of ppl in a voice channel?
i tried that too
it looks really awkward
try embed then
i didnt?
my frnd said he doesn't need embed
not u
..
something like this
sed
theyre doing the same thing, sending the image first
ohhh so sending the image first?
yeah
np
anyone?
@sullen shoal
?
!d discord.VoiceChannel.members
property members: List[Member]```
Returns all members that are currently inside this voice channel.
hey so i am trying to make a named !start to be used by 1 player in a lifetime
and i have a sql database to store info its just its creating a new record for each user
@bot.command()
async def start(ctx):
player = ctx.author
conn = sqlite3.connect('test.sql')
c = conn.cursor()
c.execute(f"INSERT INTO data VALUES ('{player.id}', 100, 0, 0, 0,'TRUE')")
c.execute(f'UPDATE data SET start_used = start_used+TRUE WHERE ID = {player.id}')
conn.commit()
await ctx.send('you have started your journey with **100:nexus:** in your balance')
if c.execute(f"SELECT * FROM data WHERE start_used=TRUE"):
return await ctx.reply("Command already used by this member.")
conn.close()
it made multiple records for the same user
make it so that it returns if they are already in there
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
include whats not working more specifically
hmmm it means something is wrong with the
if c.execute(f'SELECT......
Undefined named ctx ...
on_message cannot have ctx in it
Where should I put it?
you create a whole new record, and then check. i dont really know sqlite, so i might be wrong tho
Did
ctx means context
since its a on_message(message):
define where the message is going
.reply or .channel or (there is also a dm i forgot)
send the code
its creating a whole new record when the user uses it
https://discordpy.readthedocs.io/en/stable/ext/commands/index.html
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html?highlight=commands
the way you're making your bot is now useless, try the discord.ext.commands extension. it is better from every side.
this will later help with organizing your commands,
https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html
look at dis
2 ID's here are same because he typed the command 2 times
ctx.author.id or ctx.author.user_id?
Thx
if isinstance(ctx.author, guild.owner)
no ig
isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
Same here
tbh i never use that also
its just there was no need for me to dm or make a command for guild.owner
for my discord bot
That would just work on every Member object
Because the .author is an instance of Member and so is .owner
I'd just check if each of their ids is the same
oh yeah, i just realised
@slate swan compare the id instead
you can use == if you want to compare id
…
I think I used that before
I changed my mind on that ;-;
Good for you
The whole system is hard
💀
I can only create a very bad imaginary example that will not even work
pass list of embeds -> use reaction event -> change the index of list. Would it work in theory?
thats what pagination is.
oh..
then it should be pretty easy, just a class, a function (+ some random stuff).
what are you trying to do tho?
https://github.com/Rapptz/discord-ext-menus
can be used for reaction based paginators
which imo isnt as good as button paginators
Paginator
What is difference in between reactions and buttons for pagination
no difference, both work but one feels nicer to use
and easier to manage
Hmm I will ask in server where the bot is in at to know which one they prefer
what have i done?
wdym, troller?
“Troller” lmao 😂
Now that you said that I regret helping you
sorry dude
Idk I don’t think you can do that
how do I get messages I was mentioned/replied to in while my bot was offline? (similar to the red circle with a number of mentions on it on user accounts)
!d discord.TextChannel.history
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...
!d discord.VoiceChannel.members
property members: List[Member]```
Returns all members that are currently inside this voice channel.
@sullen shoal bruh am I supposed to do this on all channels only to check for the mentions in them?
how to use it in a program?
yes
it was offline, thats our fault
that doesn't make sense, discord gets me all the mentions even if they were one month old and very deep in the chat
that red circle with the num of mentions on it
bots are limited to see history of only like 20 days
Ignoring exception in on_command_error
Traceback (most recent call last):
File "c:\Users\phoen\OneDrive\Desktop\some-random-shit\main.py", line 1217, in help
desc = help.get(cmd)
AttributeError: 'Command' object has no attribute 'get'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\phoen\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\core.py", line 175, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\phoen\OneDrive\Desktop\some-random-shit\main.py", line 1221, in help
desc = help.get(cmd)
AttributeError: 'Command' object has no attribute 'get'```
Can someone help
what I'm saying this is that would take forever especially if you are on a lot of big servers
there must be a method to do it
channel = client.get_channel(#idhere)
members = channel.members
if len(members) >3:
#codehere
is this ok?
code plz
discord is trying to prevent people from doing it
with open('help.json') as l:
help = json.load(l)```
```py
else:
try:
desc = help.get(cmd)```
oh u mean there is a method but it's only for user accounts not for bots?
what do u want to do?
what are u tryn to do
Just pulling the json IG
@sullen shoal
no there isn't the only way is through the gui search thing which ofc bots cant replicate
Looks like you also have a command named help
@lament mesa ?
could be
I don't think that should be a issue?
ok
That will be an issue because help is a command and not a dictionary
Ah I see
Tysm
I changed it and it works
TYSM
@sullen shoal channel = client.get_channel(864103846494470154, 882287663875502152)1 is this way to get channels correct?
no
you have to iterate through the list of channel id
channel = 864103846494470154, 882287663875502152 members = channel.members if len(members) <3: await ctx.message.add_reaction('⏭') ctx.voice_state.skip()?
ctx.guild.owner
property owner: Optional[discord.member.Member]```
The member that owns the guild.
show the declaration of guild
channel = client.get_channel(864103846494470154) channel2 = client.get_channel(882287663875502152) members = channel.members if len(members) <3: await ctx.message.add_reaction('⏭') ctx.voice_state.skip() members2 = channel2.members if len(members2) <3: await ctx.message.add_reaction('⏭') ctx.voice_state.skip()
?
Oof
should work
doesn't work that way my guy
none of your tokens will work until the ratelimit is over
it doesn't care about ip once its ratelimited
yo
anyone got any ideas as to why this doesn't output anything? @bot.event async def on_reaction_add(reaction, user): if reaction.emoji == ':thumbsup:': print("he")
^
outputs this @bot.event async def on_reaction_add(reaction, user): if reaction.emoji == ':thumbsup:': print("he") which I don't understand - I removed user btw as it doesn't make sense to be there for now
outputs this ```TypeError: on_reaction_add() takes 1 positional argument but 2 were given
Is there an effective way to continuously play music from a queue? I have tried loops and realized they don't necessarily wait for the current song to finish before playing the next song.
That is, it should be able to play each song at a time and wait for the current song to finish before playing the next.
So far I have only figured out how to append the song a person choses to the queue using a "play" command
embed = nextcord.Embed(title=f"Match Records for {match}", colour = nextcord.Color.red())
embed.add_field(name="MAP", value=mapformatch, inline=True)
embed.add_field(name="MODE", value=matchmode,inline=False)
embed.add_field(name="1ST TEAM PLAYERS",value=teamonename, inline=True)
embed.add_field(name="2ND TEAM PLAYERS", value=teamtwoname, inline=True)
embed.add_field(name="WINNER", value=winner, inline=False)
await channel.send(embed=embed)```
is there any way i can move the MODE Text to near the Map text and Then the next line will have the 1stteam 2nd tea, players then next line will have the winners
is there any way i can make the embed structure like that?
!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)
async def on_reaction_add(reaction):
if reaction.emoji == ':thumbsup:':
print("he")```
outputs this
```TypeError: on_reaction_add() takes 1 positional argument but 2 were given```
..
@sullen shoal ?
idk the exact way to do it, play with it for some time maybe it will work
“Just play with it” should be the new slogan to replace “just do it”
I need a Christmas profile picture
it didnt work.. thats why came here
the code:
admin_role = get(guild.roles, name="Admin")
fetches this error:
NameError: name 'get' is not defined
this is how it gets displayed rn
idk then
Myxi
?
Hi
hello
on_reaction_add is very wonky to work with
Time to code 👨💻
iirc there's another one for "raw reactions" which doesn't need the cache or anything, use that event instead
wao
Ok
true
World Annotation Organisation?
wao = wow
damn
Wet air oxidation?
lol
💀
Wild animal orphanage
working auto oxygen
AttributeError: 'NoneType' object has no attribute 'send'
code ,-,
async def on_ready():
Channel = bot.get_channel('915552800350535750')
Moji = await Channel.send("se")
await bot.add_reaction(Moji, emoji='🏃')```
💀
Does the channel exist?
yes
bot.get_channel returns None
interesting
it's a string..
ye @velvet tinsel is right
use int not str
bot.get_channel(id_here)
It’s supposed to be an int
not bot.get_channel('id_here')
@kindred drum
yeah?
!e
yes
Yay
async def on_ready():
Channel = bot.fetch_channel(915552800350535750)
Moji = await Channel.send("se")
await bot.add_reaction(Moji, emoji='🏃')
@bot.event
async def on_reaction_add(reaction, user):
Channel = user.fetch_channel(915552800350535750)
if reaction.message.channel.id != Channel:
return
if reaction.emoji == "🏃":
Role = discord.utils.get(user.server.roles, name="Verified")
await bot.add_roles(user, Role)```
RuntimeWarning: coroutine 'Client.fetch_channel' was never awaited
pass
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
how do i make minimalhelpcommand dm user the minimal help command :troll:
await it
wait client.fetch_channel?
Why not get_channel
await what
uh
Did he just all of a sudden change the code
i did
it's get_channel im pretty sure
crab game
AttributeError: 'Bot' object has no attribute 'add_reaction'```
crab...game?
async def on_ready():
Channel = bot.get_channel(915552800350535750)
Moji = await Channel.send("se")
await bot.add_reaction(Moji, emoji='🏃')
@bot.event
async def on_reaction_add(reaction, user):
Channel = user.get_channel(915552800350535750)
if reaction.message.channel.id != Channel:
return
if reaction.emoji == "🏃":
Role = discord.utils.get(user.server.roles, name="Verified")
await bot.add_roles(user, Role)
by crab game i mean crap
yeah get_channel should work
:troll:
!d discord.get_channel
the channel works
hurrrr
but the adding the reaction doesn't
await guild.create_text_channel(f'{member} ID: {member.id}', overwrites=overwrites)
How do I get the ID of the channel that has just been created?
get_channel
@unkempt canyon goddammit
example?
I know why
oof which is
it's because you have to do bot.wait_for
😕
bot.get_channel(ID)
member = ctx.author
await member.send()
something like this @shadow wraith
I don't have the ID tho?
errrr
get the ID, ok
🤔 but this is my code
async def on_member_join(member):
guild = member.guild
role_id = 915916789152641046
admin_role = guild.get_role(role_id)
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
member: discord.PermissionOverwrite(read_messages=True),
admin_role: discord.PermissionOverwrite(read_messages=True)
}
await guild.create_text_channel(f'{member} ID: {member.id}', overwrites=overwrites)
#await channel.send("hi")
it should work
need the channel ID to send the message
class MyNewHelp(commands.MinimalHelpCommand):
async def send_pages(self):
destination = self.get_destination()
for page in self.paginator.pages:
emby = discord.Embed(description=page)
await destination.send(embed=emby)
async def on_help_command_error(error):
await destination.send("We had an error. Try running the command again.")
bot.help_command = MyNewHelp()
@slate swan https://stackoverflow.com/questions/63321098/is-it-possible-to-get-channel-id-by-name-in-discord-py
ignore on_help_command_error
it still works
even tho that is there but how do i make the bot dm the user
wait so ctx works in class 🤔
idk
grab my code and check if that works
maybe dont make a class
this will not work either
bot.help_command = commands.MinimalHelpCommand()
that will send it in the current channel but i want it to dm
bot.wait_for?
yes
which is
see this crab
how tf am i gonna get the bot to dm the user who used command
if i only hav 2 solutions
Crab game was a game made by Dani
do I need to do like await bot.wait_for(Moji)?
you want me to read it all/
@bot.event # Autobanning members and or assigning roles function!
async def on_member_join(member):
guild = member.guild
role_id = 915916789152641046
admin_role = guild.get_role(role_id)
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
member: discord.PermissionOverwrite(read_messages=True),
admin_role: discord.PermissionOverwrite(read_messages=True)
}
create_channel = guild.create_text_channel(f'{member} ID: {member.id}', overwrites=overwrites)
await(create_channel)
channelID = create_channel.id
await channelID.send("hi")
AttributeError: 'coroutine' object has no attribute 'id'
anyone know how to fix, ik whats wrong
test = bot.wait_for(on_reaction_add, check=None, timeout=None)/
don't do await(create_channel), do it on the same line as create_channels declaration
create_channel = await guild.create_text_channel(f'{member} ID: {member.id}', overwrites=overwrites)```
ok how do I fetch the ID
it should return it as long as it was awaited
so that should be create_channel.id
create_channel = await guild.create_text_channel(f'{member} ID: {member.id}', overwrites=overwrites)
channelID = create_channel.id
await channelID.send("hi")
so like that?
ah, don't send messages to the channel id
whenever you do create_text_channel, it returns the entire channel object itself
so instead do await create_channel.send("hi")
alr lemme try
the id isn't really needed in this case
yuh it worked, ty g
np
yo @slate swan you know a practical solution to this @bot.event async def on_ready(): Channel = bot.get_channel(915552800350535750) Moji = await Channel.send("se") await bot.add_reaction(Moji, emoji='🏃') @bot.event async def on_reaction_add(reaction, user): Channel = user.get_channel(915552800350535750) if reaction.message.channel.id != Channel: return if reaction.emoji == "🏃": Role = discord.utils.get(user.server.roles, name="Verified") await bot.add_roles(user, Role)
the error comes up that bot doesn't have the attribute add reaction
ah
on_reaction_add is wonky af iirc
try checking discord.py's api ref for on_raw_reaction_add
it's a bit of a pain to work with but it should work perfectly
i've had to use it before to restrict reactions on a joke bot
!d discord.Message.add_reaction not bot.add_reaction
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
i'm more surprised they got on_reaction_add working lol, i can never get it working right
that means the message isn't in cache
possibly because the message is sent before the bot's online
yeah, i had to figure that out the hard way
AttributeError: 'Member' object has no attribute 'get_channel'```
try reaction.message.guild
instead of user
oh wait, user is Member object, you can do user.guild then
await create_channel.send(input1 = input("Hello Please type somethign"))
How do I get something like this to work
how to get the list of how many commands are present in the bot?
breh from a for loop m saying
for commands in commands.Bot
do it manually?
no... with a cmd how m sayin..
🤦♂️
Just help
It’s built in
Like !help
!d discord.ext.commands.Bot.commands
property commands: Set[discord.ext.commands.core.Command[discord.ext.commands.core.CogT, Any, Any]]```
A unique set of commands without aliases that are registered.
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
hey I'm trying to make a discord bot that searches for a player in an api (https://api.hyperlandsmc.net/leaderboards)
I want it to search for a name in the site
here's my code so far
@bot.command()
async def checklb(ctx, player):
lbb = requests.get(url)
lbb = checklb.json()
lbchecker=lbb['duelelo'][player]
absolutely not stolen and modified pagination
guys, help?
errorAttributeError: module 'discord' has no attribute 'Intents'
checklb.json()?
do you have another file named discord?
should be lbb.json()
!intents || to see if it is correct
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
file?
hmm
Another object defined as discord
maybe like ```py
thithing = discord
that’s not what he meant….
oh
AttributeError: 'Guild' object has no attribute 'role'
Role = discord.utils.get(user.guild.role, name="Verified")
await user.add_role(user, Role)```
@bot.event # Autobanning members and or assigning roles function!
async def on_member_join(member):
guild = member.guild
role_id = 915916789152641046
admin_role = guild.get_role(role_id)
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
member: discord.PermissionOverwrite(read_messages=True),
admin_role: discord.PermissionOverwrite(read_messages=True)
}
create_channel = await guild.create_text_channel(f'{member} ID: {member.id}', overwrites=overwrites)
await create_channel.send("Hello Please type somethign")
computer = random.randint(1, 10)
await create_channel.send('Guess my number')
def check(msg):
return msg.author == member.author and msg.channel == member.channel and int(msg.content) in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
msg = await bot.wait_for("message", check=check)
if int(msg.content) == computer:
await create_channel.send("Correct")
else:
await create_channel.send(f"Nope it was {computer}")
Fetches this error
AttributeError: 'Member' object has no attribute 'author'
alr
roles
!helpç
AttributeError: 'Member' object has no attribute 'add_role'```
await user.add_role(user, Role)
remove author from member
Ignoring exception in command checklb:
Traceback (most recent call last):
File "C:\Users\subha\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\subha\Desktop\Good code\MAINBOT.py", line 351, in checklb
lbchecker=lbb['duelelo'][player]
TypeError: 'Response' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\subha\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\subha\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\subha\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: 'Response' object is not subscriptabl
``` error
```py
@bot.command()
async def checklb(ctx, player):
lbb = requests.get(url)
lbb.json()
lbchecker=lbb['duelelo'][player]
await ctx.send(lbchecker)
``` my cmd
roles
Hi
I wanted to ask what is the best ide for discord.py?
visual studio code
That’s not an IDE
best for everything
That’s a text editor
wait doesn't an IDE mean a text editor?
PyCharm is widely used. It’s also what I use as well.
No those are two different things.
Alright im gonna try that
Thx
VSC is just a wannabe IDE
lmao
then it just doesn't work
Ignoring exception in command checklb:
Traceback (most recent call last):
File "C:\Users\subha\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\subha\Desktop\Good code\MAINBOT.py", line 351, in checklb
lbchecker=lbb['duelelo'][player]
TypeError: 'Response' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\subha\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\subha\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\subha\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: 'Response' object is not subscriptabl
``` error
```py
@bot.command()
async def checklb(ctx, player):
lbb = requests.get(url)
lbb.json()
lbchecker=lbb['duelelo'][player]
await ctx.send(lbchecker)
``` my cmd
When something is not subscriptable that means you can’t index or slice it
oh wait ```py
url = "https://api.hyperlandsmc.net/leaderboards"
discord.errors.NotFound: 404 Not Found (error code: 10011): Unknown Role``` But I know the role is correct - ``` Role = discord.utils.get(user.guild.roles,name="Verified")```
Ignoring exception in command checklb:
Traceback (most recent call last):
File "C:\Users\subha\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\subha\Desktop\Good code\MAINBOT.py", line 351, in checklb
lbchecker=lbb['duelelo'][player]
TypeError: 'Response' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\subha\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\subha\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\subha\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: 'Response' object is not subscriptabl
``` error
```py
@bot.command()
async def checklb(ctx, player):
lbb = requests.get(url)
lbb.json()
lbchecker=lbb['duelelo'][player]
await ctx.send(lbchecker)
``` my cmd
print lbb
the response isn't like a list, you can't change it afterwards without reassigning it
try something like this:
lbb = requests.get(url).json
## or this
lbb = requests.get(url)
lbb = lbb.json()```
Now raises this:
Code:
async def on_member_join(member):
guild = member.guild
role_id = 915916789152641046
admin_role = guild.get_role(role_id)
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
member: discord.PermissionOverwrite(read_messages=True),
admin_role: discord.PermissionOverwrite(read_messages=True)
}
create_channel = await guild.create_text_channel(f'{member} ID: {member.id}', overwrites=overwrites)
await create_channel.send("Hello Please type somethign")
computer = random.randint(1, 10)
await create_channel.send('Guess my number')
def check(msg):
return msg.author == member and msg.channel == member.channel and int(msg.content) in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
msg = await bot.wait_for("message", check=check)
if int(msg.content) == computer:
await create_channel.send("Correct")
else:
await create_channel.send(f"Nope it was {computer}")
Error: AttributeError: 'Member' object has no attribute 'channel'
what do you think member.channel to be?
member is a guild user like you, it does not have a channel
Hey idk why i am getting this error with pycharm
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')]
Do you know how to fix this?
I have this error in all the codes: AttributeError: module 'discord' has no attribute 'Intents'
discord.errors.NotFound: 404 Not Found (error code: 10011): Unknown Role
await user.add_roles(user, Role)```
Not a PyCharm issue. You need to re-install discords certificates.
You need to write this before your code
intents. members = True```
check this @slate swan
it didn't help
It didn’t grab the right role then ig.
I know its correct
try again, re check it
Make sure that’s the right guild, the role exists, caps matter.
try grabbing the role based on its ID instead of its name
it is
tried this
still didn't work
same error
you sure you are giving the correct ID?
ye
if you did <@&roleid> it should give you a role mention in there, else it will say smth like "invalid role" ig
if you pass wrong role ID
perhaps try grabbing the role and using guild.get_role?
roleObj = user.guild.get_role(roleID)
await user.add_roles(roleObj)```
Cyberweapon being a pro
how come?
returns the correct role
Cyberweapon still being a pro
if you're the owner or admin of the server, go to the server settings, go to roles, find the role you're trying to use, then right click and press Copy ID
so you can be absolutely sure you're grabbing the right one
died
!
rip 💀
!role
I don’t know what’s happening so I’m just going to watch
we chillin
@kindred drum what did you want to do again?
add a role to a user, i believe
Hi guys
but utils.get wasn't working out apparently so i suggested guild.get_role and adding it to the user object
!d discord.Member.add_roles <= @kindred drum
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/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
try: ```py
role = ctx.guild.get_role(ID_OF_ROLE)
Not user, member.
ik, but his var said user
so i assumed it was a member obj
yo
Greet
🍺 or 🥛
bro my brain just shut down and i could not figure out what that second emote was lmfaoooo
1st one tho 👀
🍺
Good day mate
gamering
Greetings
I drink milk a lot
did that
i'm lactose intolerant
I don't really think so
Ofc you do
It tastes nice
did you try the guild.get_role code?
With my breakfast cereal
😳
roleObj = user.guild.get_role(roleID)
await user.add_roles(roleObj)```
cringe variable naming

bruhb
pep8 song - camelCase is not for Python
AGHGHGHHHHGHGHHAHHAAAAAAAAAAAintensescreamingsoundscontinue = 1
I like that song
^
i can't stand anything but camelCase
I prefer ςץ๒єгฬєคק𝖔ภ case
that’s like js/json naming conventions.
and i love it
Python you use snake_case
pain
I should start using my name as class name
i just use it cause it looks nice lmao
async def on_reaction_add(reaction, user):
Channel = 915552800350535750
if reaction.message.channel.id != Channel:
print(Channel)
print("invalid channel")
print(reaction.message.channel.id)
return
if reaction.emoji == "🏃":
role = discord.utils.get(user.guild.roles,name="Verified")
await user.add_roles(user, role)```
str(reaction.emoji)
cast it 2 a string
Never heard it but seen pep8 