I am using the library pyTelegramBotAPI
How can I get the user ID from the chat?
Not using a message from the user.
I know the method message.from_user.id
I need to get the id on the line
#bot.callback_query_handler(func=lambda call: True)
def callback_worker(call):
toId = call.message.chat.id
if call.data == Buttons.next:
bot.send_message(toId, Buttons.next)
elif call.data == Buttons.problem:
bot.send_message(toId, Buttons.problem)
elif call.data == Buttons.end:
bot.send_message(toId, Buttons.end)
elif call.data == Buttons.yes:
//Here I need get user_id
Related
i have script like this
def on_message(ws, message):
if str(message).split()[0] == '<open':
print('Opening Game')
print(message)
elif str(message).split()[0] == '<start':
print('Game Started')
print(message)
elif str(message).split()[0] == '<catch':
print(message)
if str(message).split()[2] == '1':
#send catch value 1
else:
pass
elif str(message).split()[0] == '<result':
print(message)
#result value of catch is '2'
else:
pass
and server send broadcast message like this
sending opening game
send start game
send random 'catch' value to client on range(1 - 100)
How can I set an condition for the next message that comes through on_message on a WebSocket stream without causing it to run on the current message?
I'm implementing a simple function in Python, but it doesn't work
Function:
# Рандомное число с кнопкой
#bot.message_handler(content_types=['text'], commands=['get_number'])
def get_number(message):
number = random.randint(0, 1000)
markup = types.InlineKeyboardMarkup()
item_yes = types.InlineKeyboardButton('Да', callback_data='yes')
item_no = types.InlineKeyboardButton('Нет', callback_data='no')
markup.row(item_yes, item_no)
bot.send_message(message.chat.id, f"<i><b>Ваше число:</b></i>\n{number}\n\nЗагадать еще раз?", reply_markup=markup,
parse_mode='html')
# Реакция на нажатие кнопки
#bot.callback_query_handler(func=lambda call: True)
def answer(call, message):
if call.data == 'yes':
pass
elif call.data == 'no':
pass
Tell me how to make it so that when you click the "Yes" button, the function is executed when you click it again, when you click "No", it stops accordingly.
I believe you can change your method:
def answer(call, message):
for
def handle_query(call):
I'm using TelegramBotAPI library to create a telegram bot in python.
I have this code to show an Inline Keyboard
def gen_markup():
markup = InlineKeyboardMarkup()
markup.row_width = 2
markup.add(InlineKeyboardButton("Yes", callback_data="cb_yes"),
InlineKeyboardButton("No", callback_data="cb_no"))
return markup
And after a function to see this keyboard when you send a command.
I have also this code to do an action when press on a button.
#bot.callback_query_handler(func=lambda call: True)
def send_welcome(call):
if call.data == "cb_yes":
bot.answer_callback_query(call.id, "YES")
elif call.data == "cb_no":
bot.send_message(call.id, "NO")
This only show the text on the screen and after some seconds it disappear. How can I send instead a text message?
Thanks
CallbackQuery contains the message object which holds chat id that can be used with send_message()
#bot.callback_query_handler(func=lambda call: True)
def callback_query(call):
if call.data == "cb_yes":
bot.answer_callback_query(call.id, "Answer is Yes")
elif call.data == "cb_no":
bot.send_message(call.message.chat.id, "This is a message")
I've been trying to add a tic-tac-toe minigame to my discord bot. I originally wrote the code inside a #client.command() because I thought you could use client.wait_for() inside it but unfortunately, you can't. Anyway, I had to convert my code to work on the on_message() function and now I am stumbling the problem of taking a discord.Member variable type from the initial command so like ~tictactoe #user#1234.
So for example, I tried writing this in the on_message() function to no success.
if message.content.startswith("~tictactoe") or message.content.startwith("~ttt"):
member = str(message).split(" ")
member = discord.Member(member[1])
channel = message.channel
Here is my full code:
if message.content.startswith("~tictactoe") or message.content.startwith("~ttt"):
member = str(message).split(" ")
member = discord.Member(member[1])
channel = message.channel
if member.bot: channel.send("You can't play against a bot!")
else:
while True:
x = 0
player = [message.author if (x % 2 == 0) else member]
x += 1
symbol = [':x:' if player == message.author else ':o:']
def check(m):
possibilities = ['a1','a2','a3','b1','b2','b3','c1','c2','c3']
return (m.content.lower() in possibilities or m.content.lower() == 'end') and m.author == player and m.channel == channel
if x != 1:
channel.send("TicTacToe\n{message.author.name} vs. {member.name}")
for i in range(3):
channel.send(f"{board[i][0]}{board[i][1]}{board[i][2]}\n")
channel.send(f"{player.mention}, where do you want to place your marker?\na1\ta2\ta3\nb1\tb2\tb3\nc1\tc2\tc3\n or `end` to end game")
try:
cell = await client.wait_for('message', timeout=20.0, check=check)
except:
channel.send("Input invalid or you took too long to respond.")
else:
cell = cell.lower()
if cell == 'end':
break
possibilities = [['a1','a2','a3'], ['b1','b2','b3'], ['c1','c2','c3']]
board = [[':black_large_square:',':black_large_square:',':black_large_square:'], [':black_large_square:',':black_large_square:',':black_large_square:'], [':black_large_square:',':black_large_square:',':black_large_square:']]
for i in range(3):
for j in range(3):
if cell == str(possibilities[i][j]): board[i][j] == symbol
won = False
for i in range(3):
if board[i][0] == board[i][1] == board[i][2] and won == False:
channel.send(f"{player} won the game!")
won == True
if board[0][i] == board[1][i] == board[2][i] and won == False:
channel.send(f"{player} won the game!")
won = True
if board[0][0] == board[1][1] == board[2][2] and won == False:
channel.send(f"{player} won the game!")
won = True
if board[0][2] == board[1][1] == board[2][0] and won == False:
channel.send(f"{player} won the game!")
won = True
Any help apperciated :)
Using message.mentions
message.mentions returns a list of discord.Member that were mentioned (or discord.User if the message in sent in private messages).
# Safe method
if message.mentions:
member = message.mentions[0]
else:
return # There was no mentions
# Riskier but simpler method
# Having no mentions or more than one would raise an error
member, = message.mentions
Quick note: a reply is considered as a mention, message.mentions will contain the members mentionned in your message and the member you replied to.
Parsing the message
A mention is equivalent to <#!id>, so you can parse your message to get the member's id:
command, member = message.split()
member_id = int(member.strip('<#!>'))
Then, to get the discord.Member object out of it:
# Regardless of cache, but sends an API call
member = await bot.fetch_member(member_id)
# Depends on the bot's cache
# Doesn't make any API calls and isn't asynchronous
member = message.guild.get_member(member_id)
I am creating a feature in my chat bot that changes the bot agent name. I declare the name of the bot at the top.
bot = "Bot"
Then I create a function that takes input from the user and changes the name of the bot
elif "c-a" in inp:
settt = True
print(f"Choose agent(1-7):", end=' ')
while settt:
s_c = input()
try:
s = int(s_c)
except ValueError:
s = str(s_c)
sv = type(s)
if sv is int:
if s == 1:
bot = "Bhaskar"
return bot
elif s == 2:
bot = "Divya"
return bot
elif s == 3:
bot = "Nayan"
return bot
elif s == 4:
bot = "Sruti"
return bot
elif s == 5:
bot = "Gagan"
return bot
elif s == 6:
bot = "Ruchi"
return bot
elif s == 7:
bot = "Abhishek"
return bot
else:
a()
print("I didn't get it. Chose between 1 to 7 or type /h for help & /q for discard")
q()
else:
if s == "/h":
bot_list()
elif s == "/q":
settt = False
else:
a()
print("I didn't get it. Chose between 1 to 7 or type /h for help & /q for discard")
q()
But the value of the bot remains the same. It will not change.
That is because the variable bot is a global.
Inside your function before the if else statements add this line
global bot
So the code would look like this:
bot = "bot"
def name():
global bot
#if else statements begin here
You should add global bot line to your function. But I suggest to avoid global variables. I think you should give it as parameter and return the changed variable.
def your_function(param=None):
... Some code (Here you can use the value of bot variable which name is param inside this function.) ...
return param
bot = your_function(param=bot)
It means you overwrite the bot variable with return value of your function.
An example:
bot = 5
print("Before function: %s" % bot)
def your_function(param=None):
param = param*2
return param
bot = your_function(param=bot)
print("After function: %s" % bot)
Output:
python test.py
Before function: 5
After function: 10