def __init__(self, starter, stopper, notification_checker, server_notification_queue, client_notification_queue, flask_app, server_actor, **kwargs): self.extra_parameters = Parameters(**kwargs) self.starter = starter self.stopper = stopper self.notification_checker = notification_checker self.flask_app = flask_app self.server_actor_ref = server_actor.start(self.flask_app) self.logger = NotificationLogger.get_logger() self.async_loop = asyncio.get_event_loop() self.updater = Updater(token=NotificationConfig.notification_token, loop=self.async_loop) self.bot = self.updater.bot self.dispatcher = self.updater.dispatcher self.running = True self.perform_check_failure_counter = 0 self.total_send_failure_counter = 0 self.notification_queue = server_notification_queue self.ack_queue = client_notification_queue
def main(): """Start the bot.""" # Bale Bot Authorization Token updater = Updater("TOKEN") # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Bale dp.add_handler(CommandHandler("start", start)) dp.add_handler(CommandHandler("help", help)) # on noncommand i.e message - echo the message on Bale dp.add_handler(MessageHandler(DefaultFilter(), echo)) # log all errors dp.add_error_handler(error) # Start the Bot updater.run()
class Bot: Config.real_time_fetch_updates = True Config.continue_last_processed_seq = False Config.timeInterval = 1 Config.updates_number = 3 # Config.log_level = 0 loop = asyncio.get_event_loop() updater = Updater(token=BotConfig.bot_token, loop=loop) bot = updater.dispatcher.bot dispatcher = updater.dispatcher
'format': "json" } response = requests.get(url=URL, params=PARAMS) Data = response.json() results = '' summary = '' for item in Data['query']['search']: summary += remove_tags(item['snippet']) + '\n' + '\n' results += "http://%s.wikipedia.org/wiki/" % language + item[ 'title'].replace(" ", "_") + '\n' return results # A token you give from BotFather when you create your bot set below updater = Updater(token="3c54b9b3f8a7698575c3e22872c4a0477ce1bb26", loop=asyncio.get_event_loop()) bot = updater.dispatcher.bot dispatcher = updater.dispatcher language = '' query = '' def success(response, user_data): # Check if there is any user data or not if user_data: user_data = user_data['kwargs'] user_peer = user_data["user_peer"] message = user_data["message"] print("message : " + message.text + "\nuser id : ", user_peer.peer_id) print("success : ", response)
"""Doc simple conversation with bot """ import asyncio from balebot.filters import * from balebot.handlers import MessageHandler, CommandHandler from balebot.models.messages import * from balebot.updater import Updater import datetime # Bale Bot Authorization Token updater = Updater(token="PUT YOUR TOKEN HERE", loop=asyncio.get_event_loop()) dispatcher = updater.dispatcher def success(response, user_data): print("success : ", response) print(user_data) def failure(response, user_data): print("failure : ", response) print(user_data) def final_download_success(result, user_data): print("download was successful : ", result) stream = user_data.get("byte_stream", None) now = str(datetime.datetime.now().time().strftime('%Y-%m-%d_%H:%M:%f'))
import asyncio from balebot.updater import Updater from PersonInformationBot.Person import Person from PersonInformationBot.postgres_database import DataBase # Config.real_time_fetch_updates=True updater = Updater (token="d821ecf310fde3a4fe485543539c53acebe3c7ae" ,loop=asyncio.get_event_loop()) dispatcher = updater.dispatcher # create database : db = DataBase() # temp person for sending information to database : person = Person("", "", 0) command_status = TextMessage command_status_strig ="" def success(result): print("success : ", result) def failure(result): print("failure : ", result) @dispatcher.command_handler(["/add", "/search"]) def conversation_starter(bot, update): message = TextMessage("hi , nice to meet you :)\nplease tell me your name.") user_peer = update.get_effective_user()
import asyncio from balebot.updater import Updater from health_care.config import BotConfig from health_care.bot.controllers import RootController loop = asyncio.get_event_loop() updater = Updater(token=BotConfig.token, loop=loop) dispatcher = updater.dispatcher RootController(dispatcher)() if __name__ == '__main__': updater.run()
from balebot.updater import Updater import asyncio from balebot.filters import PhotoFilter from balebot.handlers import MessageHandler from balebot.models.messages import TextMessage, PhotoMessage from balebot.utils.logger import Logger from combine_pictures import combine updater = Updater(token="57c74e5c2cfee9288eb579dcaf289c8191a9edd3", loop=asyncio.get_event_loop()) dispatcher = updater.dispatcher logger = Logger.get_logger() def final_download_success(result, user_data): print("d success : ", result) stream = user_data.get("byte_stream", None) user_data = user_data['kwargs'] user_peer = user_data["user_peer"] with open("hello.jpg", "wb") as file: file.write(stream) file.close() logger.info("photo saved ...") combine("hello.jpg") dispatcher.bot.send_photo(user_peer, "result.jpg", "تقدیممممم با عشققق ....:)))", "result.jpg") def success(response, user_data): user_data = user_data['kwargs']
import requests import threading from balebot.filters import * from balebot.handlers import * from balebot.config import Config from balebot.updater import Updater from balebot.models.messages import * from balebot.models.base_models import Peer from requests.packages.urllib3.exceptions import InsecureRequestWarning Config.real_time_fetch_updates = True updater = Updater(token="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA") dispatcher = updater.dispatcher bot = updater.bot requests.packages.urllib3.disable_warnings(InsecureRequestWarning) # get token def tokenize(): global headers threading.Timer(850, tokenize).start() try: tokenRequest = requests.post( 'https://beepaste.io/api/v1/auth', headers={'Content-Type': 'application/json'}, verify=False) token_json = tokenRequest.json() if token_json['status'] == 'success': token = token_json['X-TOKEN'] headers = {'X-TOKEN': token}
from balebot.utils.util_functions import get_file_buffer, get_file_size from khayyam3 import JalaliDatetime from constant.templates import BotButtons, Step, BotMessages, Patterns, LogMessage from bot.call_backs import step_success, step_failure from balebot.utils.logger import Logger from database.operations import select_all_province_names, update_money_changer_remittance_fee_percent, \ select_money_changer_by_peer_id, update_money_changer_dollar_rial, \ update_money_changer_card_number, update_money_changer_dollar_afghani, insert_to_table, \ select_branches_by_money_changer_id, delete_from_table, select_ready_money_changers, select_money_changer_by_id, \ select_last_payment_request, update_money_changer_access_hash, select_payment_with_code, update_payment_is_done, \ select_all_payments from utils.utils import * loop = asyncio.get_event_loop() updater = Updater(token=BotConfig.bot_token, loop=loop) dispatcher = updater.dispatcher logger = Logger.get_logger() # +++++++++++++++++++++++++ send_message ++++++++++++++++++++++++++++++++# def send_message(message, peer, step, succedent_message=None): bot = dispatcher.bot kwargs = { "user_peer": peer, "step_name": step, "succedent_message": succedent_message, "message": message, "attempt": 1, "bot": bot
TemplateMessage from balebot.models.messages.banking.money_request_type import MoneyRequestType from balebot.updater import Updater from Bot.alarm import Alarm from Bot.debt import Debt from Bot.template_messages import Message from balebot.models.base_models import Peer import jdatetime from DataBase.database_operations import save_alarm, search_alarm_for_send, update_alarm_time, search_stop_message, \ update_alarm_activation, check_stop_message_repetition, search_debt_for_send, save_photo, get_photo_id, \ get_photo_by_id, update_user_excel_file # global variables : loop = asyncio.get_event_loop() updater = Updater(token="63d52735b75ff858191152a038d746b956ef950e", loop=loop) dispatcher = updater.dispatcher button_list = [TemplateMessageButton("بازگشت به منوی اصلی", "/start", 0)] users_dict = {} user = None def success(result): print("success : ", result) def failure(result): print("failure : ", result)
import asyncio from balebot.filters import * from balebot.handlers import * from balebot.models.messages import * from balebot.updater import Updater from constant.message import * from db.db_handler import * from api.twitter_api import * from main.call_backs import success_send_message, failure_send_message updater = Updater(token=BotConfig.bot_token, loop=asyncio.get_event_loop()) dispatcher = updater.dispatcher logger = Logger.get_logger() def send_message(message, peer, state_name, succedent_message=None): bot = dispatcher.bot user_data = { UserData.user_peer: peer, UserData.state_name: state_name, UserData.attempt: 1, UserData.bot: bot, UserData.succedent_message: succedent_message, UserData.message: message } bot.send_message(message=message, peer=peer, kwargs=user_data,
from balebot.models.messages import PhotoMessage, TextMessage, PurchaseMessage from balebot.models.messages.banking.money_request_type import MoneyRequestType from balebot.updater import Updater from balebot.utils.util_functions import generate_random_id from sqlalchemy import cast, Date from Config import Config from ai.bale.notification_bot.models.constants import BotMessages, ResponseValue, MimeType, MessageStatus, LogMessage, \ SendingAttempt, UserData, DefaultPhoto from ai.bale.notification_bot.utils.logger import Logger from ai.bale.notification_bot.models.base import Session, engine, Base from ai.bale.notification_bot.models.message import Message my_logger = Logger.get_logger() loop = asyncio.get_event_loop() updater = Updater(token=Config.bot_token, loop=loop) bot = updater.bot dispatcher = updater.dispatcher Base.metadata.create_all(engine) session = Session() def db_pulling(): my_logger.info(LogMessage.reading_message_db) current_time = datetime.datetime.now() message_tobe_sent = session.query(Message).filter( Message.sent != MessageStatus.sent).filter( # not sent messages cast(Message.sending_time, Date) == current_time.date()).filter( Message.sending_time < current_time).all()
"""Voice and Photo simple conversation with bot """ import asyncio import base64 from balebot.filters import * from balebot.handlers import MessageHandler from balebot.models.messages import * from balebot.updater import Updater # A token you give from BotFather when you create your bot set below updater = Updater(token="6ecbbb63231ed7dbc95f4e0cd176f3951bb0b1b3", loop=asyncio.get_event_loop()) dispatcher = updater.dispatcher bot = updater.dispatcher.bot def success(response, user_data): print("success : ", response) print(user_data) def failure(response, user_data): print("failure : ", response) print(user_data) @dispatcher.command_handler(["/start"]) def conversation_starter(bot, update): message = TextMessage( "Hi , nice to meet you :)\nplease send me your photo.")
from balebot.updater import Updater from Config import Config from ai.bale.notification_bot.models.constants import Command, Attr, ResponseValue, BotMessages, Pattern, \ MessageButtonAction, \ MimeType, TransferInfo, MsgUID, LogMessage, UserData, Step, Value, SendingAttempt from ai.bale.notification_bot.utils.logger import Logger from ai.bale.notification_bot.models.base import Base, engine, Session from ai.bale.notification_bot.models.message import Message from ai.bale.notification_bot.models.notification import Notification from ai.bale.notification_bot.models.receipt import Receipt my_logger = Logger.get_logger() locale.setlocale(locale.LC_ALL, Config.system_local) updater = Updater(token=Config.bot_token, loop=asyncio.get_event_loop()) bot = updater.bot dispatcher = updater.dispatcher Base.metadata.create_all(engine) session = Session() def success(response, user_data): user_data = user_data[UserData.kwargs] user_peer = user_data[UserData.user_peer] step_name = user_data[UserData.step_name] my_logger.info(LogMessage.successful_step_message_sending, extra={ UserData.user_id: user_peer.peer_id, UserData.step_name: step_name,
#!/usr/bin/env python # -*- coding: utf-8 -*- """Purchase message simple conversation with bot.""" import asyncio from balebot.filters import * from balebot.handlers import MessageHandler from balebot.models.messages import * from balebot.models.messages.banking.money_request_type import MoneyRequestType from balebot.updater import Updater from balebot.utils.logger import Logger # Bale Bot Authorization Token updater = Updater(token="TOKEN", loop=asyncio.get_event_loop()) dispatcher = updater.dispatcher # Enable logging logger = Logger.get_logger() def success_send_message(response, user_data): kwargs = user_data['kwargs'] update = kwargs["update"] user_peer = update.get_effective_user() logger.info("Your message has been sent successfully.", extra={ "user_id": user_peer.peer_id, "tag": "info" })
"""Simple hear with your bot""" import asyncio from balebot.filters import * from balebot.models.messages import TextMessage from balebot.updater import Updater # A token you give from BotFather when you create your bot set below updater = Updater(token="e20d43ca38ff6095acbf4a83fcc92f6a635f382f") # Define dispatcher dispatcher = updater.dispatcher # Both of success and failure functions are optional def success(result, user_data): print("success : ", result) print(user_data) def failure(result, user_data): print("failure : ", result) print(user_data) # hear function @dispatcher.message_handler(filters=DefaultFilter() ) # filter text the client enter to bot def hear(bot, update): print("hiiiiiiiiiii")
"""Purchase message simple conversation with bot """ import asyncio from balebot.filters import * from balebot.handlers import MessageHandler from balebot.models.messages import * from balebot.models.messages.banking.money_request_type import MoneyRequestType from balebot.updater import Updater # A token you give from BotFather when you create your bot set below updater = Updater(token="PUT YOUR TOKEN HERE", loop=asyncio.get_event_loop()) dispatcher = updater.dispatcher bot = updater.dispatcher.bot def success(response, user_data): print("success : ", response) print(user_data) def failure(response, user_data): print("failure : ", response) print(user_data) @dispatcher.command_handler(["/start"]) def conversation_starter(bot, update): message = TextMessage("Hi , nice to meet you :)\nplease send me a photo") user_peer = update.get_effective_user()
class Bot: loop = asyncio.get_event_loop() updater = Updater(token=BotConfig.bot_token, loop=loop) bot = updater.dispatcher.bot dispatcher = updater.dispatcher