Altcoins Talks - Cryptocurrency Forum

Local => Philippines (Tagalog) => Mga palitan at crypto sites => Topic started by: Scofield on November 11, 2020, 10:01:27 AM

Title: Algorand - Pagpapatupad ng Telegram sa Python; Patakbuhin ang iyong Dapp ASAP
Post by: Scofield on November 11, 2020, 10:01:27 AM
PINAGMULAN NG PAGSASALIN (https://www.publish0x.com/ddev-at-algorand/algorand-telegram-implementation-in-python-get-your-dapp-run-xkklrjx)
By: Ddev


(https://i.imgur.com/ySwBEBl.jpg)

Mula sa pagsulat ng mga code sa disenyo ng application hanggang sa pag-deploy ay maaaring maging mahirap lalo na kung ikaw ay baguhan sa industriya. Ako ay nasa kategoryang ito at gusto ko galugarin araw-araw upang makita kung paano ko magagawa ang aking sarili na nauugnay sa mundo sa pamamagitan ng paggawa ng isang bagong bagay at sa ibang paraan, marahil ang karamihan sa mga bagay na ginagawa natin ay hindi talaga bago sa ilalim ng kalangitan ngunit kung paano natin ito ginagawa at ang resulta ay mahalaga. Let's hit the nail on the head.

Ang Telegram ay isang messaging application na may kamangha-manghang end to end na pag-encrypt na nagdudulot ng kasikatan nito sa ngayon. Halos bawat application na ginagamit namin ay simpleng human-machine (programs). Nag-input ka o nag-hit ng isang command button at isang mensahe ang ipinadala pabalik sa iyo. Ganito gumagana ang bot ng Telegram. Tumawag ka ng mga command, habang nagsasagawa ito sa background ng ilang mga proseso at ibabalik sa iyo ang resulta. Kung naghahanap ka para sa application na may napakalaking user base upang madagdagan ang visibility para sa iyong negosyo, produkto, serbisyo o proyekto, isaalang-alang mo ang paggalugad sa Telegram.

Ang Algorand (https://algorand.com/)ay isang kumpanya ng teknolohiya na nagtayo at bumuo ng kauna-unahang bukas, permissionless, pure proof-of-stake na blockchain protocol sa mundo, nang walang forking, nagbibigay ng kinakailangang seguridad, sclability, at desentralisasyon na kinakailangan para sa ekonomiya ngayon. Sa pamamagitan ng isang award-winning na koponan, pinapagana namin ang traditional finance at decentralized financial na mga kumpanya upang yakapin ang mundo ng frictionless finance.

TANDAAN: Ang solusyon na ito ay available sa format ng video sa pagtatapos ng artikulong ito.


Ang solusyon na ito ay kasama ng bersyon ng video na ilalabas ko kaagad pagkatapos mai-release ang artikulong ito. Ang mga bagay na mai-exposed sa iyo ay:
Mga Kinakailangan


Ipinag-papalagay ko na na-install mo ang lahat ng nakalista sa itaas na mga kinakailangan. Gamit ang application na ito, magagawa ng mga user ang mga sumusunod na mga function na ma-run sa Algorand Testnet:
Una, kakailanganin natin ang isang pagkakakilanlan sa Telegram na maaari mong makuha mula sa Bot father.
(https://i.imgur.com/1En68IQ.jpg)


Buksan ang iyong editor, inirerekumenda ko ang Pycharm kung hindi mo pa ginagamit ang isa. I-import ang mga kinakailangang module. Kailangan mong i-pamilyar muna sa iyong sarili sa kung ano ang ginagawa ng package at/o ng mga module upang magamit ito nang mabisa. Tumungo sa github.


Code: [Select]
# Create a python file called connection.py and paste the following code.
# To get the url and the token, sign up on purestake.com
from algosdk.v2client import algod

url = "https://testnet-algorand.api.purestake.io/ps2"
algod_token = "ALGOD TOKEN HERE"


def connect():
    # Using the third party API
    algod_url = url
    algod_auth = algod_token  # os.environ.get('ALGODTOKEN')
    headers = {"X-API-Key": algod_token}
    try:
        return algod.AlgodClient(algod_auth, algod_url, headers)
    except Exception as e:
        print(e)


algod_client = connect()
params = algod_client.suggested_params()

Code: [Select]
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Import the necessary modules.
import logging
from algosdk import account, mnemonic
from connection import algod_client
from telegram import (ReplyKeyboardMarkup, InlineKeyboardButton,  InlineKeyboardMarkup)
import time
import os

from telegram.ext import (
    Updater,
    CommandHandler,
    CallbackQueryHandler,
    Filters,
    ConversationHandler,
    PicklePersistence,
)

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)

# Use the token you got from bot father here
TOKEN = <YOUR_BOT_TOKEN_HERE>

# Displays these as commands when the start command is invoked
reply_keyboard = [
    ['/Create_account', '/Get_Mnemonics_from_pky'],
    ['/Query_account_balance', '/Account_status', '/enquire'],
    ['/About', '/help', '/Done'],
]
# Maps the above parameters to the keyboard, so when user clicks on any, it is captured
# as command
markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)

# Utility that instantiates conversation with the bot
# Must pass in "update" and "context as parameters to every declared/defined functions
# update.message.from_user gets all updates from a user including name and username in
# Json format, so we are stripping the user's username.

# 'context.user_data' temporarily stores all entries from user. It can be used as a way
# to collect input from users. It is always in Json format.
# Here we clear the user_data storage to ensure that we are not using existing data in
# place of current one since we will mostly be working with current data. So each time a
# user restarts the bot, we have an empty dictionary.
def start(update, context):
    user = update.message.from_user
    reply = "Hi {}! I am ALGOMessenger.".format(user['first_name'])
    reply += (
        "I can help you with a few things.\n"
        "Tell me what you need to do.\nThey should be from the menu.\n"
        "\nSend: \n"
        "/Create_account to Create an account.\n"
        "/Get_Mnemonic_from_pky to Get Mnemonic words from private key.\n"
        "/Transfer to Transfer asset.\n"
        "/Balance to Query account balance.\n"
        "/Account_status to Check your account status.\n"
        "Send /Done to cancel conversation."
        "Use /start to test this bot."
    )
    update.message.reply_text(reply, reply_markup=markup)
    context.user_data.clear()
    print(context.user_data)

# A polite way for ending a session.
def end_chat(update, context):
    update.message.reply_text(
        "Your current session is terminated.\n"
        "Click /start to restart."
    )
    return ConversationHandler.END


# Returns the status of an account when called
# When called, gets the user's existing address abd return the status of the account as
# at when called, then end the session.
def account_status(update, context):
    """

    :param update: Telegram's default param
    :param context: Telegram's default param
    :param address: 32 bytes Algorand's compatible address
    :return: Address's full information
    """
    pk = context.user_data['default_pk']
    status = algod_client.account_info(pk)
    for key, value in status.items():
        update.message.reply_text("{} : {}".format(key, value))
        time.sleep(0.7)
    return ConversationHandler.END

# Generates a private and public key and return them to the user.
# update.message.reply() sends message in text format to the user.
# On returning the keys to user, it informs them to get a testnet Algo for the purpose
# of testing this bot.
def create_account(update, context):
    """
    Returns the result of generating an account to user:
        - An Algorand address
        - A private key.
    """
    update.message.reply_text("Hang on while I get you an account ...")
    time.sleep(2)
    sk, pk = account.generate_account()
    update.message.reply_text("Your address:   {}\nPrivate Key:    {}\n".format(pk, sk))
    update.message.reply_text(
        "Keep your mnemonic phrase from prying eyes.\n"
        "\nI do not hold or manage your keys."
    )
    context.user_data['default_sk'] = sk
    context.user_data['default_pk'] = pk
    if context.user_data.get('default_pk') == pk and context.user_data['default_sk'] == sk:
        update.message.reply_text("Account creation success.")
    else:
        update.message.reply_text('Account creation error\n.')
    print(context.user_data)
    time.sleep(1.5)
    update.message.reply_text('To test if your address works fine, copy your address, and visit:\n ')
    keyboard = [[InlineKeyboardButton(
        "DISPENSER", 'https://bank.testnet.algorand.network/', callback_data='1')]]

    reply_markup = InlineKeyboardMarkup(keyboard)

    update.message.reply_text('the dispenser to get some Algos', reply_markup=reply_markup)

    update.message.reply_text("Session ended. Click /start to begin.")
    return ConversationHandler.END


# Function to convert private key to mnemonic phrase
def get_mnemonics_from_sk(update, context):
    """
    Takes in private key and converts to mnemonics
    :param context:
    :param update:
    :return: 25 mnemonic words
    # """
    sk = context.user_data['default_sk']
    print(sk)
    phrase = mnemonic.from_private_key(sk)
    update.message.reply_text(
        "Your Mnemonics:\n {}\n\nKeep your mnemonic phrase from prying eyes.\n"
        "\n\nI do not hold or manage your keys.".format(phrase), reply_markup=markup
    )
    update.message.reply_text('\nSession ended.')
    return ConversationHandler.END

# Check user's account and return the current total balance with pending rewards.
# When called. it takes user's existing account address, performs the query operation
# and return the result to user.
def query_balance(update, context):
    pk = context.user_data['default_pk']
    print(pk)
    update.message.reply_text("Getting the balance on this address ==>   {}.".format(pk))
    if len(pk) == 58:
        account_bal = algod_client.account_info(pk)['amount']
        update.message.reply_text("Balance on your account: {}".format(account_bal))
    else:
        update.message.reply_text("Wrong address supplied.\nNo changes has been made.")
        context.user_data.clear()
    return ConversationHandler.END


# Inline bot utility, can be used for polling, links etc.
def enquire(update, context):
    keyboard = [[InlineKeyboardButton("Website", 'https://algorand.com', callback_data='1'),
                 InlineKeyboardButton("Developer'site", 'https://developer.algorand.org', callback_data='2')],

                [InlineKeyboardButton("Community", 'https://community.algorand.com', callback_data='3')]]

    reply_markup = InlineKeyboardMarkup(keyboard)

    update.message.reply_text('Learn more about Algorand:', reply_markup=reply_markup)


def button(update, context):
    query = update.callback_query

    # CallbackQueries need to be answered, even if no notification to the user is needed
    # Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery
    query.answer()

    query.edit_message_text(text="Selected option: {}".format(query.data))


# help() provides guide when user needs help.
def help_command(update, context):
    update.message.reply_text("Use /start to test this bot.")


# On completion of a task, it clears the context and end the session.
def done(update, context):
    # call_transfer = transfer(update, context)
    # update.message.reply_text("{}".format(call_transfer))
    if 'choice' in context.user_data:
        del context.user_data['choice']
        context.user_data.clear()
        return ConversationHandler.END
    update.message.reply_text(
        "Swift! Your transaction is completed,", reply_markup=markup
    )
    return ConversationHandler.END



Code: [Select]
# Here is the application logic that determines how the code should run.
def main():
    # Create the Updater and pass it your bot's token.
    pp = PicklePersistence(filename=<specify a name for here>)#can be any valid name.
    updater = Updater(TOKEN, persistence=pp, use_context=True)

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

    #For example, sending a /start command triggers the 'start' function
    # This is done using the Commandhandler module.
    dp.add_handler(CommandHandler('start', start))
    dp.add_handler(CommandHandler('Create_account', create_account))
    dp.add_handler(CommandHandler('Get_Mnemonics_from_pky', get_mnemonics_from_sk))
    dp.add_handler(CommandHandler('Query_account_balance', query_balance))
    dp.add_handler(CommandHandler('Account_status', account_status))
    dp.add_handler(CommandHandler('Done', end_chat))
    dp.add_handler(CommandHandler('About', enquire))
    dp.add_handler(CallbackQueryHandler(button))
    dp.add_handler(CommandHandler('help', help_command))
    dp.add_handler(CommandHandler('enquire', enquire))

    # 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()


Ngayon na tapos na tayo sa pag-coding, ilalagay natin ang code upang ang sinuman ay maaaring makipag-ugnay sa bot. Sa susunod na sesyon, ipapakita ko sa iyo kung paano mag-deploy sa isang cloud tulad ng Heroku.




Pagkatapos ng pag-deploy, buksan ang application ng Telegram, maghanap para sa relorobot o Algobot20. Magsimula ng isang pag-uusap dito..

(https://i.imgur.com/wKzhpbj.jpg)


(https://i.imgur.com/3dN2nGD.jpg)


(https://i.imgur.com/1h54taj.jpg)


(https://i.imgur.com/t65Nu32.jpg)


(https://i.imgur.com/VzXhZJN.jpg)


(https://i.imgur.com/odvMSyV.jpg)


Sa puntong ito, gumagana nang tama ang ating bot. Nagagawa nating:


Empasis
Ang key na aalisin dito ay hindi pagkakaroon ng kamalayan sa mabilis, smooth at matalinong paraan na maaari mong isulat at mai-deploy sa isang desentralisadong mga application/samart contract sa Algorand blockchain nang hindi kinakailangang dumaan sa isang maraming proseso ng paglikha ng isang buong pangkaraniwan na application. Tandaan na ito ay isang tip lamang ng kung ano ang maaari mong likhain gamit ang paradigm na ito. Sa darating na artikulo, ipapakita ko sa iyo kung paano ka maaaring sumulat ng smart contract, mag-deploy at makipag-interact dito sa pamamagitan ng Telegram.

Ang buong code ay available sa Github (https://github.com/bobeu/algobot). Kung mayroon kang mga katanungan, mangyaring mag-iwan ng komento.

Video


Mga mapagkukunan

Website (https://algorand.com/)

Developer Site (https://developer.algorand.org/)

I-download ang Python (https://python.org/)