-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlab4
67 lines (55 loc) · 2.67 KB
/
lab4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
## chatbot.py
from telegram import Update
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
# The messageHandler is used for all message updates
import configparser
import logging
import redis
global redis1
def main():
# Load your token and create an Updater for your Bot
config = configparser.ConfigParser()
config.read('telbotassignment.ini')
updater = Updater(token=(config['TELEGRAM']['ACCESS_TOKEN']), use_context=True)
dispatcher = updater.dispatcher
global redis1
redis1 = redis.Redis(host=(config['REDIS']['HOST']), password=(config['REDIS']['PASSWORD']), port=(config['REDIS']['REDISPORT']))
# You can set this logging module, so you will know when and why things do not work as e
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO)
# register a dispatcher to handle message: here we register an echo dispatcher
echo_handler = MessageHandler(Filters.text & (~Filters.command), echo)
dispatcher.add_handler(echo_handler)
# on different commands - answer in Telegram
dispatcher.add_handler(CommandHandler("add", add))
dispatcher.add_handler(CommandHandler("help", help_command))
dispatcher.add_handler(CommandHandler('hello', hello))
# To start the bot:
updater.start_polling()
updater.idle()
def echo(update, context):
reply_message = update.message.text.upper()
logging.info("Update: " + str(update))
logging.info("context: " + str(context))
context.bot.send_message(chat_id=update.effective_chat.id, text= "hello")
# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def help_command(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /help is issued."""
update.message.reply_text('Helping you helping you.')
def hello(update: Update, context: CallbackContext) -> None:
"""Send a greeting message when the command /hello is issued."""
arugs = context.args
name = " ".join(arugs)
update.message.reply_text(f"Good day, {name}!")
def add(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /add is issued."""
try:
global redis1
logging.info(context.args[0])
msg = context.args[0] # /add keyword <-- this should store the keyword
redis1.incr(msg)
update.message.reply_text('You have said ' + msg + ' for ' +redis1.get(msg).decode('UTF-8') + ' times.')
except (IndexError, ValueError):
update.message.reply_text('Usage: /add <keyword>')
if __name__ == '__main__':
main()