Ada*_*dam 1 python python-telegram-bot telegram-bot
I've downloaded this open-source code from GitHub which is written in Python(that I'm pretty new to it), I wanted to make my bot to have a Custom-Keyboard instead of letting users say whatever they wanted. for instance if user start the chat with my bot, they will automatically send /start and when this happens I want my bot to give them two to three options ['Option One'], [Option Two], on keyboard, when they choose one of those options, I want to have totally different options (for instance ['Plan A'], ['Plan B'],). And again when they choose one of them, they get different options on their keyboard, and so on.
class WebhookHandler(webapp2.RequestHandler):
def post(self):
urlfetch.set_default_fetch_deadline(60)
body = json.loads(self.request.body)
logging.info('request body:')
logging.info(body)
self.response.write(json.dumps(body))
update_id = body['update_id']
try:
message = body['message']
except:
message = body['edited_message']
message_id = message.get('message_id')
date = message.get('date')
text = message.get('text')
fr = message.get('from')
chat = message['chat']
chat_id = chat['id']
if not text:
logging.info('no text')
return
def reply(msg=None, img=None):
if msg:
resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
'chat_id': str(chat_id),
'text': msg.encode('utf-8'),
'disable_web_page_preview': 'true',
})).read()
else:
logging.error('no msg or img specified')
resp = None
logging.info('send response:')
logging.info(resp)
if text.startswith('/'):
if text == '/start':
reply('Bot enabled')
setEnabled(chat_id, True)
elif text == '/stop':
reply('Bot disabled')
setEnabled(chat_id, False)
else:
reply('That ain\'t been coded yet.')
Run Code Online (Sandbox Code Playgroud)
As I said I'm virgin to Pyhton, and I'd be so thankful if you applied your code to the code that's above this text, instead of giving me ideas(which I wouldn't know how to use them, and get the work done!).
小智 7
首先,我建议您使用一些模块来使用它。由于您是新手,因此python-telegram-bot可以为您提供帮助。
好吧,假设您将使用它,则有两种选择:
您可以在选项为命令的地方创建键盘。
def start(bot, update):
kb = [[telegram.KeyboardButton('/command1')],
[telegram.KeyboardButton('/command2')]]
kb_markup = telegram.ReplyKeyboardMarkup(kb)
bot.send_message(chat_id=update.message.chat_id,
text="your message",
reply_markup=kb_markup)
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)
Run Code Online (Sandbox Code Playgroud)创建文本选项并使用正则表达式对其进行过滤。
def start(bot, update):
kb = [[telegram.KeyboardButton("Option 1")],
[telegram.KeyboardButton("Option 2")]]
kb_markup = telegram(chat_id=update.message.chat_id,
text="your message",
reply_markup=kb_markup)
start_handler = RegexHandler('some-regex-here', start)
dispatcher.add_handler(start_handler)
Run Code Online (Sandbox Code Playgroud)但是,您不能阻止用户发送他想要的任何其他消息。您只能忽略消息,仅对命令或键盘响应进行回复。
| 归档时间: |
|
| 查看次数: |
7946 次 |
| 最近记录: |