i need the list of countries that are supported africa's talking api - api

I actually want to use Africa's talking api on my ussd app. I am from bangladesh and i am confused if it supports bangladesh or not.there are mainly four service provider in bangladesh namely gameenphone, robi, banglalink, airtel. I want to send ussd from one of the operator to my application.
here is python code:
from flask import Flask, request
import africastalking
import os
app = Flask(__name__)
username = "sandbox"
api_key = "*384*89376#"
africastalking.initialize(username, api_key)
sms = africastalking.SMS
#app.route('/', methods=['POST', 'GET'])
def ussd_callback():
global response
session_id = request.values.get("sessionId", None)
service_code = request.values.get("serviceCode", None)
phone_number = request.values.get("phoneNumber", None)
text = request.values.get("text", "default")
sms_phone_number = []
sms_phone_number.append(phone_number)
#ussd logic
if text == "":
#main menu
response = "CON What would you like to do?\n"
response += "1. Check account details\n"
response += "2. Check phone number\n"
response += "3. Send me a cool message"
elif text == "1":
#sub menu 1
response = "CON What would you like to check on your account?\n"
response += "1. Account number"
response += "2. Account balance"
elif text == "2":
#sub menu 1
response = "END Your phone number is {}".format(phone_number)
elif text == "3":
try:
#sending the sms
sms_response = sms.send("Thank you for going through this tutorial",
sms_phone_number)
print(sms_response)
except Exception as e:
#show us what went wrong
print(f"Houston, we have a problem: {e}")
elif text == "1*1":
#ussd menus are split using *
account_number = "1243324376742"
response = "END Your account number is {}".format(account_number)
elif text == "1*2":
account_balance = "100,000"
response = "END Your account balance is USD {}".format(account_balance)
else:
response = "END Invalid input. Try again."
return response
if __name__ == "__main__":
app.run()

Africa's Talking USSD services are in the following countries:
Kenya,
Uganda,
Tanzania,
Rwanda,
Nigeria
Côte d'Ivoire,
Malawi,
Zambia,
South Africa
Hope this helps. Reach out if you have any more questions.

Related

telethon :A wait of 16480 seconds is required (caused by ResolveUsernameRequest)

i'm trying to use telethon to send messages to telegram groups. after some times runing, it reruens:
A wait of 16480 seconds is required (caused by ResolveUsernameRequest).
the code is:
async def main():
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
config = configparser.ConfigParser()
config.read("seetings.ini",encoding= 'utf-8')
message = config['Customer']['message']
internal = config['Customer']['internal']
count = 0
excel_data = pandas.read_excel('tg_groups.xlsx', sheet_name='Groups')
for column in excel_data['GroupUsername'].tolist():
try:
if str(excel_data['GroupUsername'][count]) == 'None':
count += 1
continue
else:
chat = await client.get_input_entity(str(excel_data['GroGroupUsernameupID'][count]))
await client.send_message(entity=chat, message=message)
except Exception as e:
print(e)
time.sleep(int(internal))
count = count + 1
continue
time.sleep(int(internal))
count = count + 1
if __name__ == '__main__':
if proxytype == 'HTTP':
print('HTTP')
client = TelegramClient('phone'+phone, api_id, api_hash, proxy=(socks.HTTP, 'localhost', int(proxyport))).start()
if proxytype == 'socks5':
print('SOCKS5')
client = TelegramClient('phone'+phone, api_id, api_hash, proxy=(socks.SCOKS5, 'localhost', int(proxyport))).start()
myself = client.get_me()
print(myself)
freqm = config['Customer']['freq']
print(int(freqm))
while True:
with client:
client.loop.run_until_complete(main())
time.sleep(int(freqm))`
`
from the 'Entity' guide, it says get_input_entity method will search the user info from session file cache, why it it still call the 'ResolveUsernameRequest'to get the user info? anything i missed?
thanks for any advice.
'Entity' guide, it says get_input_entity method will search the user info from session file cache, why it it still call the 'ResolveUsernameRequest'to get the user info? anything i missed or the session file didn't keep the user info cache?

pyTelegramBotAPI.How to edit/delete message with inline buttons only if message from the same step was already in chat?

I want my TG bot to have inlinebuttons with categories and subcategories in chat with dynamic change.
But how to send message with subcategories if it doesnt exist and edit message with subcategories if it already exists?
Also, I wish to have a "back" inlinebutton among categories that will delete messages with categories and subcategories and turn to main menu.
Attached my code and illustration of goal.
Help me please!
import telebot
from telebot import types
bot = telebot.TeleBot(TELEGRAM_TOKEN,
parse_mode=None)
markup_menu = types.ReplyKeyboardMarkup(resize_keyboard=True)
btns = ["Order"]
for btn in btns:
markup_menu.add(types.KeyboardButton(btn))
menu = {"Snacks": {"Sweet Snack": 150, "Salt snak": 320}, "Drinks": {"Cola": 100, "Sprite": 90},
"Meat": {"Pork": 228, "Beef": 56}}
#bot.message_handler(commands=['start'])
def start(message):
bot.send_message(message.chat.id,
f"Wellcome, <b>{message.from_user.first_name}</b>",
reply_markup=markup_menu,
parse_mode="html")
#bot.message_handler(content_types="text")
def order(message):
# These are variable values to help change next message after "Choose category:"
order_counter = 0
product_message = 0
switcher = {product_message: order_counter}
if message.text == 'Order':
order_menu = types.InlineKeyboardMarkup()
order_menu.row_width = 2
for category in menu:
order_menu.add(types.InlineKeyboardButton(category,
callback_data=f"{category}"))
bot.send_message(message.chat.id,
"Choose category:",
reply_markup=order_menu)
if order_counter == 0:
#bot.callback_query_handler(func=lambda call: call.data in menu.keys())
def callback_product(call):
product_menu = types.InlineKeyboardMarkup()
product_menu.row_width = 4
for product in menu[call.data]:
product_menu.add(types.InlineKeyboardButton
(f"{product}" +
f" - {menu[call.data][product]}",
callback_data=f"{product}")
)
product_message = bot.send_message(message.chat.id,
f'Choose {call.data}:',
reply_markup=product_menu,
)
product_message
order_counter == 1
switcher = {product_message: order_counter}
return switcher
elif switcher.keys() == 1:
#bot.callback_query_handler(func=lambda call: call.data in menu.keys())
def callback_product1(call):
product_menu = types.InlineKeyboardMarkup()
product_menu.row_width = 4
for product in menu[call.data]:
product_menu.add(types.InlineKeyboardButton
(f"{product}" +
f" - {menu[call.data][product]}",
callback_data=f"{product}")
)
product_message = bot.edit_message_text(chat_id=switcher[0][0].message.chat.id,
message_id=switcher[0][0].message_id,
text=f'Choose {call.data}:',
reply_markup=product_menu
)
product_message
order_counter == 1
return order_counter, product_message
#bot.message_handler(content_types="text")
def missunderstand(message):
bot.reply_to(message, "I don't understand you", reply_markup=markup_menu)
bot.infinity_polling()
I have tried to create a switcher that would signal to func. if message with subcategories exists, but it didn't work. (it's "switcher" in code)

How to receive multiple messages in python-telegram-bot?

I am sending multiple images at a time to a bot in telegram. I am trying to create a conversational chatbot using python-telegram bot.
here is my code:
def main():
updater = Updater("1141074258:Axxxxxxxxxxxxxxxxxxxxxxxxg", use_context=True)
dp = updater.dispatcher
conv_handler = ConversationHandler(
entry_points = [CommandHandler('start',start)],
states = {
CHOSEN_OPTION: [MessageHandler(Filters.regex('^(Option2|Option3|Option4)$'),choose_option)],
PRODUCTS: [MessageHandler(Filters.text | Filters.photo,products)],
Option2: [MessageHandler(Filters.text,option2)],
Option3: [MessageHandler(Filters.text,option3)],
Option4: [CommandHandler('create', create_order)]
},
fallbacks=[CommandHandler('cancel', cancel)]
)
dp.add_handler(conv_handler)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
#run_async
def products(update,context):
logger.info("update is %s",update)
input_message = update.message.text
if input_message:
data['products'] = input_message
logger.info("product text is:%s",input_message)
elif update.message.photo:
photo_list = []
bot = context.bot
length = len(update.message.photo)
for photo in range(0,length):
ident = update.message.photo[photo].file_id
getFile = context.bot.get_file(ident)
photo_list.append(getFile['file_path'])
data['products_image'] = photo_list
update.message.reply_text("Please type name.",)
return Option3
If i am send 2 images same time, i am getting one image with a different size (3 times), How can I receive the actual two messages?
if update contains photo return PRODUCTS for getting other photos else
get text and return to every state you want
#run_async
def products(update,context):
logger.info("update is %s",update)
if update.message.photo:
# to what you want with your photos
return PRODUCTS
if update.message.text:
# getting product text
return Option3

I can't figure out, how to set up webhook on pyTelegramBotApi (telebot)

I've done exactly, like in this official example: https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/webhook_examples/webhook_aiohttp_echo_bot.py. Nothing seems to work, though. It doesn't crush either.
WEBHOOK_URL in format http://adress.io. WEBHOOK_PATH = '/'.
import telebot
from aiohttp import web
from config import *
from messages import *
bot = telebot.TeleBot(TOKEN)
app = web.Application()
bot.remove_webhook()
bot.set_webhook(url=WEBHOOK_URL + WEBHOOK_PATH)
async def handle(request):
if request.match_info.get('token') == bot.token:
request_body_dict = await request.json()
update = telebot.types.Update.de_json(request_body_dict)
bot.process_new_updates([update])
return web.Response()
else:
return web.Response(status=403)
# main loop
if __name__ == '__main__':
#bot.message_handler(content_types=['text'])
def reply(message):
if message.text == "/start":
bot.send_message(message.from_user.id, MESSAGE_START)
elif message.text == "/help":
bot.send_message(message.from_user.id, MESSAGE_HELP)
elif message.text == "/seeagreement":
bot.send_message(message.from_user.id, MESSAGE_AGREEMENT)
web.run_app(
app,
host=WEBHOOK_IP,
port=WEBHOOK_PORT,
)
I'm a newbie to telegram api and telebot, but i saw this question has no answers so im gonna put what i think may help you find it out (or for whoever that faces this question)
I decided to deploy my bot to Heroku, done everything it wanted but got a weird error that 'TeleBot' doesn't have 'message_handler' attr, but no error for webhook found. so i'm just gonna explain what i did.
I used CPython code instead of aiohttp that you used. Your code with some changes will become this (the changes aren't exactly the same with source code so take a look at it):
import telebot
from http.server import BaseHTTPRequestHandler, HTTPServer
from config import *
from messages import *
bot = telebot.TeleBot(TOKEN)
WEBHOOK_HOST = '<ip/host where the bot is running>'
WEBHOOK_PORT = int(os.environ.get('PORT', 5000))
WEBHOOK_LISTEN = '0.0.0.0'
WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT)
WEBHOOK_URL_PATH = "/%s/" % (TOKEN)
async def handle(request):
if request.match_info.get('token') == bot.token:
request_body_dict = await request.json()
update = telebot.types.Update.de_json(request_body_dict)
bot.process_new_updates([update])
return web.Response()
else:
return web.Response(status=403)
# main loop
if __name__ == '__main__':
#bot.message_handler(content_types=['text'])
def reply(message):
if message.text == "/start":
bot.send_message(message.from_user.id, MESSAGE_START)
elif message.text == "/help":
bot.send_message(message.from_user.id, MESSAGE_HELP)
elif message.text == "/seeagreement":
bot.send_message(message.from_user.id, MESSAGE_AGREEMENT)
httpd = HTTPServer((WEBHOOK_LISTEN, WEBHOOK_PORT), WebhookHandler)
httpd.serve_forever()
worked fine for me. Hope it helps you or anyone else that is reading this.
PS. I'm gonna switch to telegram pkg (the main api) because of that error (and where i live, i can't use any foreign host and it's so expensive here. just gonna stick to Heroku to see if it works)

How do I structure this medium sized flask application?

Using the FLASK framework in Python, my application needs to:
register and log in users (with either a sqlite or postgres database)
access a specific google spreadsheet that the logged in user owns and output that data in a json format.
I am required to have my own authorization & authentication system
I am having a lot of trouble figuring out how to even structure the application - what directories and sub-directories should I have?
I have done A LOT of playing around (about 1 months worth). I am using a virtual environment but don't know how to test my code well either. In general, my code runs but I have no idea how they work together really.** I am completely new to flask.**
Structuring the app:
|app
|----run.py
|----config.py
|----database
|---------database.db
|----app
|---------views.py
|---------models.py
|---------forms.py
|---------extensions.py
|----templates
|---------....
|----static
|--------....
Authorization / Authentication:
I have looked at Flask-Login, Flask-Auth, Flask-Security. I understand the general idea but do not know how to securely implement a complete authorization & authentication system.
app = Flask(__name__)
app.config.from_object(config)
login_manager = LoginManager()
login_manager.init_app(app)
def create_app():
db.init_app()
db.app = app
db.create_all()
return app
#app.route('/')
def index():
#needs to render the homepage template
#app.route('/signup', methods = ['GET', 'POST'])
def register():
form = SignupForm()
if request.method == 'GET':
return render_template('signup.html', form=form)
elif request.method == 'POST':
if form.validate_on_submit():
if User.query.filter_by(email=form.email.data).first():
return "email exists"
else:
newuser = User(form.email.data, form.password.data)
db.session.add(newuser)
db.session.commit()
login_user(newuser)
return "New User created"
else:
return "form didn't validate"
return "Signup"
#app.route('/login', methods = ['GET', 'POST'])
def login():
form = SignupForm()
if request.method == 'GET':
return render_template('login.html', form=form)
elif request.method == 'POST':
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user:
if user.password == form.password.data:
login_user(user)
return "you are logged in"
else:
return "wrong password"
else:
return "user doesnt exist"
else:
return "form did not validate"
#login_manager.user_loader
def load_user(email):
return User.query.filter_by(email = email).first()
#app.route('/protected')
#login_required
def protected():
return "protected area for logged in users only"
if __name__ == '__main__':
#app.create_app()
app.run(port=5000, host='localhost')`
from flask_security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin, login_required
import os
# Create app
app = Flask(__name__)
#app.config['DEBUG'] = True
app.config['SECRET_KEY'] = ''
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////'
app.config['SECURITY_PASSWORD_HASH'] = 'sha512_crypt'
app.config['SECURITY_PASSWORD_SALT'] = str(os.urandom(24))
# Create database connection object
db = SQLAlchemy(app)
# Define models
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))
class Role(db.Model, RoleMixin):
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(80), unique=True)
description = db.Column(db.String(255))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
confirmed_at = db.Column(db.DateTime())
roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'))
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)
# Create a user to test with
#app.before_first_request
def create_user():
db.create_all()
user_datastore.create_user(email='', password='')
db.session.commit()
#app.route('/')
#login_required
def home():
#password = encrypt_password('mypass')
#print verify_and_update_password('mypass', password)
return "hello"
if __name__ == '__main__':
app.run(debug=True, use_reloader=False)
** I would really appreciate any guidance!**
Project structure:
If you're planning to build a larger Flask application, you should consider decomposing the functionality into Blueprints.
The official Flask documentation has a tutorial on how to structure larger applications:
http://flask.pocoo.org/docs/0.12/patterns/packages/
Also, take a look at the Hitchhiker's guide to organizing your project. It has some very good points: http://python-guide-pt-br.readthedocs.io/en/latest/writing/structure/
If you're designing an REST API consider using Flask-RESTful (which also works nicely with Blueprints)
ya'll, i figured it out & my app is LOOKING GOOD :)I am using blueprints & an application factory pattern.
APP
|_runserver.py
|_/app
|---__init__.py
|---config.py
|---extensions.py
|---forms.py
|---models.py
|---/login_dashboard #blueprint
|------__init__.py
|------views.py
|------/templates
|---------base.html
.
.
|------/static
|-----------/css
.
.
|-----------/js
.
.
|-----------/img
.
.