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)
Related
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 am trying out the python telegram bot. I am trying to pass the state from button to questionTwo. However, when I run it, it can successfully pass through /start and answerOne. Yet, it will stop at answerOne by displaying it.
It will not display the second question and inline keyboard for me to select the answer, I believe the state didn't pass to questionTwo, but I am not sure which part is wrong. Thank you in advanceb
import logging
from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove,InlineKeyboardButton, InlineKeyboardMarkup)
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters,
ConversationHandler,CallbackQueryHandler)
answerOne, answerTwo = range(2)
def start(update, context):
keyboard = [
[
InlineKeyboardButton("Option 1", callback_data='1'),
InlineKeyboardButton("Option 2", callback_data='2'),
],
[InlineKeyboardButton("Option 3", callback_data='3')],
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text('Please choose:', reply_markup=reply_markup)
return answerOne
def button(update, context):
query = update.callback_query
# CallbackQueries need to be answered, even if no notification to the user is needed
# Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery
query.answer()
query.edit_message_text(text="Selected option: {}".format(query.data))
return questionTwo
def questionTwo(update, context):
keyboard = [
[
InlineKeyboardButton("Option 4", callback_data='4'),
InlineKeyboardButton("Option 5", callback_data='5'),
],
[InlineKeyboardButton("Option 6", callback_data='6')],
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text('Please choose:', reply_markup=reply_markup)
return answerTwo
def answerTwo(update, context):
query = update.callback_query
# CallbackQueries need to be answered, even if no notification to the user is needed
# Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery
query.answer()
query.edit_message_text(text="Selected option: {}".format(query.data))
def cancel(update, context):
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():
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater('TOKEN', use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
answerOne: [CallbackQueryHandler(button)],
questionTwo:[MessageHandler(Filters.text & ~Filters.command, questionTwo)],
answerTwo:[CallbackQueryHandler(answerTwo)],
},
fallbacks=[CommandHandler('cancel', cancel)]
)
dp.add_handler(conv_handler)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
import logging
from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove,InlineKeyboardButton, InlineKeyboardMarkup)
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters,
ConversationHandler,CallbackQueryHandler)
answerOne, questionTwo = range(2)
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)
def start(update, context):
keyboard = [
[
InlineKeyboardButton("Option 1", callback_data='1'),
InlineKeyboardButton("Option 2", callback_data='2'),
],
[InlineKeyboardButton("Option 3", callback_data='3')],
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text('Please choose:', reply_markup=reply_markup)
return answerOne
def button(update, context):
query = update.callback_query
# CallbackQueries need to be answered, even if no notification to the user is needed
# Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery
query.answer()
query.edit_message_text(text="Selected option: {}".format(query.data))
return questionTwo
def questionTwo(update, context):
keyboard = [
[
InlineKeyboardButton("Option 4", callback_data='4'),
InlineKeyboardButton("Option 5", callback_data='5'),
],
[InlineKeyboardButton("Option 6", callback_data='6')],
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text('Please choose:', reply_markup=reply_markup)
return answerOne
def cancel(update, context):
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():
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater('Token', use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
answerOne: [CallbackQueryHandler(button)],
questionTwo:[MessageHandler(Filters.text & ~Filters.command, questionTwo)]
},
fallbacks=[CommandHandler('cancel', cancel)]
)
dp.add_handler(conv_handler)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
I am trying to show a popup message to user using the task module. I have sent a attachment with type invoke. Here is the code
content.sendActivity(MessageFactory.attachment(CardFactory.heroCard('Task Module Invocation from Hero Card',
'This is a hero card with a Task Module Action button',
null, // No images
[{ type: 'invoke', title: 'Task Module', value: { type: 'task/fetch' } }])));
When I click on the Button I have received a request to my messaging end point and the response I have sent is
reply({
task: {
type: 'continue',
value: {
"title": "Task module title",
"height": 'large',
"width": 'large',
"url": "https://67aa9b57.ngrok.io/api/internal/teams/tabs/content",
"fallbackUrl": "https://67aa9b57.ngrok.io/api/internal/teams/tabs/content"
}
}
});
But in the popup message is blank. My ngrok url is not even being hit for the HTML page. This is what I see in popup. But the title was updated. I have no idea why it is not working.
Ant help would be thankful
This is pretty much always caused by the domain of the page not being listed in the valid domains for the application (you set this in your manifest json file, inside App Studio if you're using it). Because you've not listed this as a valid and "safe" domain, Teams won't even make any call at all, that's why there's nothing visible in the NGrok log even.
Just to be clear, we're talking about this section of the schema.
I need to change the name of [chat] header bot to Askme.
may i know how to change it in Microsoft bot.
Image is attched
Alternatively, if you want to set it at the time of initialization and are using the Botchat.App() setup rather than the iframed version of webchat, you can set this in the parameter object sent to webchat:
BotChat.App({
botConnection: botConnection,
user: { id: '1234', name: 'user'},
bot: { id: 'bot' },
chatTitle: "I'm a custom chat title"
}, document.getElementById("bot"));
The key parameter in this case being chatTitle; other options that can be sent to webchat can be found in the source code right here.
If you are not using the iframe'd webchat, you can just modify the header's .innerHTML like this:
var header = document.getElementsByClassName("wc-header");
header[0].innerHTML = "<span>Askme</span>"