You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

10 KiB

In [23]:
import logging
import json

from telegram import ReplyKeyboardMarkup, Update
from telegram.ext import (
    Updater,
    CommandHandler,
    MessageHandler,
    Filters,
    ConversationHandler,
    PicklePersistence,
    CallbackContext,
)
In [24]:
# Enable logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)

logger = logging.getLogger(__name__)


CHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3)

#Create bot keyboard
reply_keyboard = [
    ['/start','I would Submit a Translation'],
    ['Want an Explaination', 'Go to the Project'],
    ['Done'],
]

markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
In [25]:
def facts_to_str(user_data):
    facts = list()

    for key, value in user_data.items():
        facts.append('{}'.format(value))

    return "\n".join(facts).join(['\n', '\n'])
In [26]:
# the bot starts here

def start(update: Update, context: CallbackContext) -> None:
    first_name = update.message.from_user['first_name']
    reply_text = f"Hi, {first_name}! This is Practical Vision Bot."
    update.message.reply_text(reply_text, reply_markup=markup)

    return CHOOSING
In [27]:
#function for submitting

def submit(update: Update, context: CallbackContext) -> None:
    text = update.message.text.lower()
    context.user_data['choice'] = text
    #if context.user_data.get(text):
    #    reply_text = 'Your {}, I already know the following ' 'about that: {}'.format(
    #        text, context.user_data[text]
    #    )
    #else:
    reply_text = f'Super! Please, respect the following format: \n\n english, translation, which-language \n\n For Example: \n hello, ciao, italian \n\n I would suggest you to translate `Practical Vision` :) !'.format(text)
    update.message.reply_text(reply_text)

    return TYPING_REPLY
In [28]:
#function for explaination

def exp(update: Update, context: CallbackContext) -> None:
    first_name = update.message.from_user['first_name']
    update.message.reply_text(f"`PRACTICAL VISION: the fresh opportunity for disseminating African literature that the digital age makes possible.` (Ngũgi wa Thiongo) \n\n The future should be multi-lingual: this Telegram BOT makes a crowd-sourced dictionary with your translations. \n You can add every word/sentence you want from english to be translated into any language! \n Soon you will be able to have a look to the dictionary.", reply_markup= markup)   
In [29]:
#function for link proj

def project(update: Update, context: CallbackContext) -> None:
    update.message.reply_text(f"Here it is! \n \n https://issue.xpub.nl/13/PRACTICAL_VISION/printing \n Made with love from Federico Poni \n in the context of https://issue.xpub.nl/13 \n\n Made with love from XPUB1",  reply_markup= markup)
In [30]:
#function for echo submission

def received_information(update: Update, context: CallbackContext) -> None:
    first_name = update.message.from_user['first_name']
    text = update.message.text
    category = context.user_data['choice']
    context.user_data[category] = text.lower()
    del context.user_data['choice']
    prova = context.user_data[category]
    
    if ',' not in prova:
        update.message.reply_text(f"Hey, it was wrong".format(facts_to_str(context.user_data)),
        reply_markup=markup,
    )
        return CHOOSING
        
    else:
        appending = prova.replace(' ','').split(',')
    
    
    
    f = open('PracticalDictionary.json',)

    data = json.load(f)

    if appending[0] not in data:
        data[appending[0]] = {appending[2]:appending[1]}
    elif appending[0] in data:
        data[appending[0]][appending[2]] = appending[1]

    dictionary = data

    with open("PracticalDictionary.json", "w") as outfile: 
        json.dump(dictionary, outfile) 

    
    update.message.reply_text(f"Cool {first_name}!" " You have just submitted" "{}" "You can submit more translations, if you want :)".format(facts_to_str(context.user_data)),
        reply_markup=markup,
    )

    return CHOOSING
In [ ]:
 
In [31]:
#function for echo everything submitted

def show_data(update: Update, context: CallbackContext) -> None:
    update.message.reply_text(
        "This is what you already told me:" "{}".format(facts_to_str(context.user_data))
    )
In [32]:
#function for end bot and echo everything submitted

def done(update: Update, context: CallbackContext) -> None:
    update.message.reply_text(
        "This is what you submitted today:" 
        "{}".format(facts_to_str(context.user_data)),reply_markup=markup,
    )
    return ConversationHandler.END
    
In [ ]:
 
In [ ]:
def main():
    # Create the Updater and pass it your bot's token.
    pp = PicklePersistence(filename='conversationbot')
    updater = Updater("1452534708:AAERTrbN_LUDSLkf0J8sJjvMEEuwfRNka50", persistence=pp, use_context=True)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY
    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('start', start)],
        states={
            CHOOSING: [
                MessageHandler(Filters.regex('^Want an Explaination$'), exp),
                MessageHandler(Filters.regex('^Go to the Project$'), project),
                MessageHandler(Filters.regex('^I would Submit a Translation$'), submit)
                ],
            TYPING_CHOICE: [
                MessageHandler( Filters.text & ~(Filters.command | Filters.regex('^Done$')), start)
            ],
            TYPING_REPLY: [
                MessageHandler(Filters.text & ~(Filters.command | Filters.regex('^Done$')), received_information)
            ]
        },
        fallbacks=[MessageHandler(Filters.regex('^Done$'), done)],
        name="my_conversation",
        persistent=True,
    )
    
    dp.add_handler(conv_handler)

    show_data_handler = CommandHandler('show_data', show_data)
    dp.add_handler(show_data_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()
2020-12-07 12:36:35,085 - apscheduler.scheduler - INFO - Scheduler started
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]: