How to use an emoji as prefix instead of "/" on Telebot - python

I'm trying to write a Telegram bot to help a friend with his online buisness.
I'm trying to make an interactive menu, but if I try to use an emoji as a prefix the #bot.message_handler doesn't read the user input, resulting in the menu not updating.
Working code (with "/" as command prefix):
#bot.message_handler(commands=["Menu"])
def startMenu(msg):
#########-START MENU-#########
markup = keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True, one_time_keyboard=True)
btnHelp = types.KeyboardButton("/Help")
##############################
markup.add(btnHelp)
bot.send_message(msg.chat.id, text="Need help?"
, reply_markup=markup)
#bot.message_handler(commands=["Help"])
def helpMenu(msg):
markup = keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True, one_time_keyboard=True)
btnBack = types.KeyboardButton("/Menu")
markup.add(btnBack)
bot.send_message(msg.chat.id, text="Test Help"
, reply_markup=markup)
Faulty code (with UNICODE emoji as prefix):
#bot.message_handler(commands=["Menu"])
def startMenu(msg):
#########-START MENU-#########
markup = keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True, one_time_keyboard=True)
btnHelp = types.KeyboardButton("\U0001F60Help")
##############################
markup.add(btnHelp)
bot.send_message(msg.chat.id, text="Need help?"
, reply_markup=markup)
#bot.message_handler(commands=["\U0001F60Help"])
def helpMenu(msg):
markup = keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True, one_time_keyboard=True)
btnBack = types.KeyboardButton("/Menu")
markup.add(btnBack)
bot.send_message(msg.chat.id, text="Test Help"
, reply_markup=markup)

You can use regular expression as there is no native way to change the prefixes:
#bot.message_handler(regexp="^\U0001F60H(your_command)")

Related

Discord-component button help interaction failed

So im using this code and i have from discord_components import * and DiscordComponents(bot) in on_ready. I did pip install --update discord-components. This is the code im using.
#bot.command()
async def button(ctx):
await ctx.channel.send(
"This is a button test :smile:",
components =[
Button(style=ButtonStyle.blue, label ="Button 1"),
Button(style=ButtonStyle.red, label ="Button 2"),
Button(style=ButtonStyle.URL, label ="this is a picture", url="https://www.planetware.com/wpimages/2020/02/france-in-pictures-beautiful-places-to-photograph-eiffel-tower.jpg" ),
],
)
component = discord.Component
interaction1 = await client.wait_for("button_click", check = lambda i: i.component.label.startswith("Button 1"))
await interaction1.respond(content = "Button 1 Seems like it working")
interaction2 = await client.wait_for("button_click", check = lambda i: i.component.label.startswith("Button 2"))
await interaction2.respond(content = "Button 2 Seems like it working")
There is no error message and when I do $button it prints but if I click on a button it says interaction failed(still no error message) I'm new to button so if you could help me that would be great

This Interaction Failed - Discord_components - Discord.py

Hello I recently made a help command using discord_components buttons (I know they arent fully supported by Discord.py) but I still went ahead. The problem is that whenever I run the command and receive the Buttons to click on, they alway say "This Interaction Failed". I can't seem to find what's wrong. Please help.
Thanking You,
NightMX.
import discord
from discord.ext import commands
from discord_components.component import ButtonStyle
from discord_components import DiscordComponents, Button, Select, SelectOption
from discord_components.interaction import InteractionType
class BotCommands(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def helpv2(self, ctx):
funbutton = Button(style=ButtonStyle.grey, label="Fun Commands", id="funcmds")
monkedevbutton = Button(style=ButtonStyle.grey, label="Attachment Commands", id="monkecmds")
# utilitybutton = Button(style = ButtonStyle.grey, label = "3", id = "embed3")
funembed = discord.Embed(title="Fun Commands", colour=discord.Colour.orange())
funembed.add_field(name="k.joke", value="Sends a Random joke from PyJokes")
monkedevembed = discord.Embed(title="Fun Commands", colour=discord.Colour.blurple())
monkedevembed.add_field(name="k.dog", value="Sends a Random Dog Fact")
monkedevembed.add_field(name="k.monkey", value="Sends a Monkey's Picture")
monkedevembed.add_field(name="k.bird", value="Sends a Bird's Picture")
await ctx.send(
"Kola's Beta Help Command!",
components=[[funbutton, monkedevbutton]]
)
buttons = {
"funcmds": funembed,
"monkedcmds": monkedevembed
}
while True:
event = await self.bot.wait_for('button_click')
if event.channel is not ctx.channel:
return
if event.channel == ctx.channel:
response = buttons.get(event.component.id)
if response is None:
await event.channel.send(
"Something went Wrong"
)
if event.channel == ctx.channel:
await event.respond(
type=InteractionType.ChannelMessageWithSource, embed=response
)
def setup(client):
client.add_cog(BotCommands(client))
should be content="something" instead of embed = response

checkbox inline button in aiogram python

i have this aiogram inline buttons
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from middlewares.internationlization import _
choise_sign_select_company = InlineKeyboardMarkup(row_width=1,
inline_keyboard=[
[
InlineKeyboardButton(
text=_('Капитализация ❌'),
callback_data='market_cap_of_company'
),
InlineKeyboardButton(
text=_('Кол-во акций ❌'),
callback_data='count_shares_ofustanding_of_company'
)
],
[
InlineKeyboardButton(
text=_('Цена акции ❌'),
callback_data='current_prise_share_now_of_company'
)
]
])
how to turn these buttons into a check of a button? For example, so that when you click on the "Capitalization ❌" button, the button changes to "Capitalization ✅" (when you click it again, it goes back)
and also the value was stored in the call.data from callback_data
Here comes the keyboard
#dp.message_handler(text='Подобрать компании 🤑')
async def select_sign(message: types.Message):
await message.answer(_('Выберите признаки на которых будет основываться подбор'),
reply_markup=choise_sign_select_company)
await SelectCompanies.enter_the_sign.set()
click on the button is processed here
#dp.callback_query_handler(state=SelectCompanies.enter_the_sign)
async def select_interval(call: types.CallbackQuery):
text = call.data
await call.answer(text)
You can manually implement this feature using callbacks.
For example, store current button`s state in callback and change it after click.
Also, there is aiogram-dialog library. You can find special "checkbox" button there
You can try it:
from aiogram_dialog import DialogManager, ChatEvent
from aiogram_dialog.widgets.kbd import Checkbox, ManagedCheckboxAdapter
from aiogram_dialog.widgets.text import Const
async def check_changed(event: ChatEvent, checkbox: ManagedCheckboxAdapter, manager: DialogManager):
print("Check status changed:", checkbox.is_checked())
check = Checkbox(
Const("✓ Checked"),
Const("Unchecked"),
id="check",
default=True, # so it will be checked by default,
on_state_changed=check_changed,
)

Telegram Bot with multi-stage menu without sending messages

Can somebody help, I cant understand how can I do my bot with two menus.
first - is "short menu" where you press the button and its open "long menu" with all functions
second - in "long menu" menu where I have all functions and the button "Back to Menu".
I cant understnand how to make the button "Back to Menu" that go back me to the "short menu"
help me please. And the Main -- the clicking on buttons should not send a message to the user
def telegram():
with open("madata") as f3:
info = yaml.safe_load(f3)
token = mytoken
bot = Bot(token=token)
dp = Dispatcher(bot)
#greeting message, pin this message in private chat
#dp.message_handler(commands=['start'])
async def greeting(message: types.Message):
chat_id = message.chat.id
msg = '''hello friend'''
# body of keyboard
small_function = ReplyKeyboardMarkup(
keyboard = [
[
KeyboardButton(text="show functions", callback_data='open menu all functions')
]
],
resize_keyboard=True
)
all_functions = ReplyKeyboardMarkup(
keyboard = [
[
KeyboardButton(text="function 1", callback_data='do function1')
],
[
KeyboardButton(text="function 2", callback_data='do function2')
],
[
KeyboardButton(text="back to menu", callback_data=' open menu small_function')
],
],
resize_keyboard=True
)
#insert my keyboard
sent_message = await bot.send_message(chat_id=chat_id, text=msg,parse_mode = "Markdown", reply_markup=small_function)
print(sent_message.message_id)
#bot.callback_query_handler(func=lambda call: True)
async def answer(call):

How to add dividers to rumps menu

I have made a python script which creates a MacOS Status bar item which displays youtube statistics.
I want to add dividers to the drop down menu when you click the text but I am unable to do this. (Image of what I mean under the text). I have found many examples but all of them only work with an __init__ function in the class. If I try adding an __init__ function to the class I get an error saying AttributeError: 'Sub_Counter' object has no attribute '_menu'. Why is this happening and how can it be fixed?
Code I added to the __init_ function
self.menu = [
"About",
"No Icon",
None,
"Detailed Statistics:",
None,
"Quit",
]
Normal Code without the __init__ function
import rumps
import time
import sys
import os
from sty import fg
from googleapiclient.discovery import build
key = open(os.path.join(sys.path[0], './key.txt')).read().strip()
service = build('youtube', 'v3', developerKey=key)
subs = service.channels().list(
part='statistics',
id='UCERizKQbgpBXOck0R6t_--Q'
).execute()['items'][0]['statistics']['subscriberCount']
timers = ["1 secs","5 secs","10 secs","15 secs","20 secs","25 secs","30 secs","35 secs","45 secs","50 secs","1 Min"]
EXEC_TIMER = 60
class Sub_Counter(rumps.App):
#rumps.timer(EXEC_TIMER)
def pull_data(self, _):
self.sub_menu = timers
subs = service.channels().list(
part='statistics',
id='UCERizKQbgpBXOck0R6t_--Q'
).execute()['items'][0]['statistics']['subscriberCount']
a = (str(subs))
self.icon = "logo.png"
self.title = "Subscribers: " + str(a)
self.notification = str(a) + " Subscribers"
#rumps.clicked("About")
def about(self, _=):
rumps.notification("Youtube Subscriber Count", "Made by Roxiun using Python & rumps", "Shows Youtube Subscriber counts")
#rumps.clicked("No Icon")
def noicon(self, sender):
sender.state = not sender.state
self.icon = None
#rumps.clicked("Detailed Statistics")
def Detailed_Statistics(self, _):
rumps.notification("You have:", self.notification , "Veiws Comming Soon")
if __name__ == "__main__":
Sub_Counter("Loading...").run() #debug=True
Image of what I want to do [circled in red - (Yes it is the line)]
Thanks in advance!
Fixed by doing
app = Sub_Counter("Loading...")
app.menu[
"About",
"No Icon",
None,
"Detailed Statistics:",
None,
"Quit",
]
app.run()
You can add a separator by doing:
self.menu.add(rumps.separator)
Link to source code.

Categories