I want a command to remove the role from everyone who owns it. I tried like below and it doesn't work. Can anyone help me.
`
#commands.command()
async def keyall(self, ctx):
guild = ctx.guild
role1 = discord.utils.get(guild.roles, name="test1")
role2 = discord.utils.get(guild.roles, name="test2")
role3 = discord.utils.get(guild.roles, name="key 3")
roles = {role1, role2, role3}
for user in guild.members:
for role in roles:
if role in user.roles:
await user.remove_roles(role)
`
Instead using guild.members, you can use role.members. So the command only ranged for member who had that role. For those documentation you can check here
#commands.command()
async def removerole(self, ctx):
role_name_list = ['role1', 'role2', 'etc..']
for role_name in role_name_list:
role = get(ctx.guild.roles, name=role_name)
for member in roles.members:
await member.remove_roles(role)
Related
I am creating a bot discord in discord.py v2 and I have created app commands. I would like to make some commands reserved to administrators or to a certain role, but I didn't find how to do it. #commands.has_permissions does not work for app commands.
Can someone tell me how to do this please ?
My code :
#app_commands.command(name="embed_message", description="Create a embed message")
#app_commands.describe(
title="The title of your message",
message="Your message",
color="Embed color",
image="Add an image to your message (with image's url : http(s)://...)",
url="Add an url to your message (http(s)://....)"
)
#app_commands.choices(color=[Choice(name="🔴 Red", value=0xff0000),
Choice(name="🔵 Blue", value=0x0000ff),
Choice(name="🟢 Green", value=0x00ff00),
Choice(name="🟣 Purple", value=0x883af1),
Choice(name="🟡 Yellow", value=0xffe34d),
Choice(name="🟠 Orange", value=0xff8000),
Choice(name="🟤 Brown", value=0x845321),
Choice(name="⚫️ Black", value=0xffffff),
Choice(name="⚪️ White", value=0x000000),
])
#commands.has_permissions(administrator=True)
async def embed_message(self, interaction = discord.Interaction, title:str="", message:str="", image:str="", url:str="", color:int=0xff0000):
await interaction.response.defer()
if title!="" or message!="":
embed = discord.Embed(title = title, description = message, color = color)
if image!="":
embed.set_thumbnail(url=image)
if url!="":
embed.url=url
await interaction.followup.send(embed=embed)
else:
await interaction.followup.send("You must enter at least one title or message", ephemeral=True)
Using this decorator before the slash command worked for me:
#app_commands.checks.has_permissions(moderate_members=True)
(swap in your required permissions)
Hi I Try to make Logger Bot in discord.py
My Code:
#client.event
async def on_guild_role_create(guild, role):
logs = await guild.audit_logs(limit=1, action=discord.AuditLogChanges.role_create).flatten()
channel = guild.get_channel(channel_ID)
logs = logs[0]
if logs.target == role:
#await channel.send(f'{logs.user} Created Role.')
Error I Got:
Ignoring exception in on_guild_role_create
Traceback (most recent call last):
File "C:\Users\MY PC\AppData\Roaming\Python\Python38\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\MY PC\source\repos\Event\Event\Event.py", line 32, in on_guild_role_create
logs = await guild.audit_logs(limit=1, action=discord.AuditLogChanges.role_create).flatten()
AttributeError: 'Role' object has no attribute 'audit_logs'
What should I do?
on_guild_role_create only takes in one parameter, the role. We have to get the guild instance form the role.
async def on_guild_role_create(role):
guild = role.guild
#other stuff here
References:
role.guild
on_guild_role_create
i am stuck in my code as i do not know how to input/derive the message_id of the outgoing message forwarded by my bot.
Background: This is just a part of my code which i would subsequently integrate into the main code. Here, i am testing the functionality of forwarding messages + deleting them. I am able to successfully forward them out but i am stuck at deleting them. i am able to give the input of the chat_id but not able to do so for the message_id to delete. Is there a way to do it especially when i am gonna integrate to my main script which can have a few groups to manage. Please assist the noob in me. Thank you!
My script:
import logging
from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, Update
from telegram.ext import (
Updater,
CommandHandler,
MessageHandler,
Filters,
ConversationHandler,
CallbackContext,
)
TOKEN = "PUT TOKEN HERE" #INPUT HERE
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
MSG, DELETE_MSG = range(2)
def start(update: Update, context: CallbackContext) -> int:
update.message.reply_text(
'Hi! Please post the message you would like to share:')
return MSG
def send(update: Update, context: CallbackContext) -> int:
user = update.message.from_user
logger.info("Message of %s: %s", user.first_name, update.message.text)
print(update.message.message_id)
send = update.message.forward(chat_id= 'PUT CHAT ID OF OUTGOING GROUP HERE') #INPUT HERE
update.message.reply_text("Please delete")
return DELETE_MSG
def delete_msg(update: Update, context: CallbackContext) -> int:
user = update.message.from_user
logger.info("edit of %s: %s", user.first_name, update.message.text)
update.message.delete(chat_id='PUT CHAT ID OF OUTGOING GROUP HERE',
message_id='IM STUCK HERE') #INPUT HERE
return ConversationHandler.END
def cancel(update: Update, context: CallbackContext) -> int:
user = update.message.from_user
logger.info("User %s canceled the conversation.", user.first_name)
update.message.reply_text('Bye! I hope we can talk again some day.', reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END
def main() -> None:
updater = Updater(TOKEN, use_context=True)
dispatcher = updater.dispatcher
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
MSG: [MessageHandler(~Filters.command, send)],
DELETE_MSG: [MessageHandler(~Filters.command, delete_msg)]
},
fallbacks=[CommandHandler('cancel', cancel)],
)
dispatcher.add_handler(conv_handler)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
update.message.reply_text("Please delete") must be a variable and, then, you'll be able to context.bot.deleteMessage the message_id of that. Just like this:
must_delete = update.message.reply_text("Please delete")
context.bot.deleteMessage (message_id = must_delete.message_id,
chat_id = update.message.chat_id)
Give it a try and let me know if this worked for you!!
enter image description hereI have a command that checks the info about a given player and bot. The last error is when showing activity and member, because when you enter a member that is available, it shows that he is unavailable.
I use this command: member.status
`client = discord.Client()
intents = discord.Intents.default()
intents.presences = True
client = commands.Bot(command_prefix="q.", intents=intents)
client.remove_command('help')
#client.command()
async def getname(ctx, member: discord.Member = None):
member = ctx.author if not member else member
roles = [role for role in member.roles]
embed = discord.Embed(
clour=member.color, timestamp=ctx.message.created_at, color=0x00ff00)
embed.set_author(name=f"Nazwa użytkownika: {member}")
embed.set_thumbnail(url=member.avatar_url)
embed.set_footer(
text=f"Utworzony {ctx.author}", icon_url=ctx.author.avatar_url)
embed.add_field(name="ID", value=member.id)
embed.add_field(name="Pseudomin", value=member.display_name)
embed.add_field(
name="Konto Utworzone:",
value=member.created_at.strftime("%d.%m.%Y,%H:%M.%S"))
embed.add_field(
name="Dołączył:", value=member.joined_at.strftime("%d.%m.%Y,%H:%M.%S"))
embed.add_field(
name=f"Rola ({len(roles)})",
value=" ".join([role.mention for role in roles]))
embed.add_field(name="Najwyższa rola", value=member.top_role.mention)
embed.add_field(name="Status", value=member.status)
embed.add_field(name="Aktywność", value=member.activity)
embed.add_field(name="Bot", value=member.bot)
embed.add_field(name="Status mobilny", value=member.mobile_status)
embed.add_field(name="Nitro", value=member.premium_since)
embed.add_field(name="Kolor nazwy", value=member.color)
embed.add_field(name="Kanał Głosowy", value=member.voice)
embed.add_field(name="Status na komputerze", value=member.desktop_status)
await ctx.send(embed=embed)
`
You should activate the server members intents from the discord developer portal for your bot, then you must give your bot the accessibility like below:
intents = discord.Intents(members = True, presences = True)
client = commands.Bot(command_prefix="q.", intents=intents)
I'm trying to use Google Classroom API, I've read through their documentation, and the course ID is used for basically everything, but they never explained where to find the course ID for a course.
It also seems like when you create a course, the function would return the course ID, but I'm wondering if it's possible to get the course ID for courses that already exist.
As shown in the quickstart page for the documentation (https://developers.google.com/classroom/quickstart/python), you can run a piece of code to list the first 10 courses the user has access to with their credentials. You can then add a print(course['id']) statement whilst iterating through the courses to print the id of the courses you have retrieved. The python example is shown below
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/classroom.courses.readonly']
def main():
"""Shows basic usage of the Classroom API.
Prints the names of the first 10 courses the user has access to.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('classroom', 'v1', credentials=creds)
# Call the Classroom API
results = service.courses().list(pageSize=10).execute()
courses = results.get('courses', [])
if not courses:
print('No courses found.')
else:
print('Courses:')
for course in courses:
print(course['name'])
print(course['id'])
if __name__ == '__main__':
main()
I use this in nodejs/javascript to retrieve all classroom
const { google } = require("googleapis");
const classroom = google.classroom('v1');
const SCOPES = [
"https://www.googleapis.com/auth/classroom.rosters",
"https://www.googleapis.com/auth/classroom.profile.emails",
"https://www.googleapis.com/auth/classroom.profile.photos",
"https://www.googleapis.com/auth/classroom.courses"
];
google.options({
auth: client,
});
//retrieve all classroom
async function getClassroom() {
try {
const res = await classroom.courses.list(
// {
// pageSize: 10,
// pageToken: "",
// }
);
console.log(res.data, "res");
} catch (error) {
console.error("Error:", error.message,);
}
}
Note: The client is my preferred authorization method