def __init__(self): """Икапсулирует работу СППР и взаимодействие с человеком-оператором.""" # Create fields self._detect_frame = None self._last_frame = None self._score = -1 self._events = [] self._decisions = {} self._id = None self._offset = 0 self._state = States.Disconnected # Load config with open('config.json', 'r', encoding='utf-8') as f: self._config = json.loads(f.read()) # Init fields self._post_time = datetime.now() - timedelta( seconds=10 * self._config['timeouts']['detection']) self.__register_events(2) # Create bot self._bot = Bot(token=self._config['telegram']['token'], request=request.Request( proxy_url=self._config['telegram']['proxy']['url'], urllib3_proxy_kwargs=self._config['telegram'] ['proxy']['auth'])) # Set log file as <module name>.log logging.basicConfig( format=u'%(levelname)-8s [%(asctime)s] %(message)s', level=logging.INFO, filename=sys._getframe(0).f_code.co_filename.replace( '<', '').replace('>', '') + '.op.log')
def start_collector(bot): a = request.Request().retrieve(url='https://api.telegram.org/bot{}/getUpdates'.format(config.token)).decode("utf-8") data = json.loads(str(a)) if len(data['result']) > 0: for i in range(len(data['result'])): auth = db.SQLighter('db.sqlite') unique_id = int(data['result'][i]['message']['message_id']) cur_time = int(data['result'][i]['message']['date']) user_id = int(data['result'][i]['message']['from']['id']) bot.send_message(chat_id=user_id, text=sent_repeat['RU']) try: news_text = str(data['result'][i]['message']['text']) bot.send_message(chat_id=user_id, text=news_text) auth.insert_lost_news(unique_id, cur_time, user_id, news_text=news_text, file_id=None) except KeyError: try: photo = str(data['result'][i]['message']['photo'][-1]['file_id']) bot.send_photo(chat_id=user_id, photo=photo) auth.insert_lost_news(unique_id, cur_time, user_id, news_text=None, file_id=photo) except KeyError: try: auth.insert_lost_news(unique_id, cur_time, user_id, news_text=None, file_id=None) except KeyError: pass else: pass
def __init__(self, config: Dict[str, int] = None): """Создать нового телеграмм-бота. config - сопоставление командам id. {'command':id}""" self._operator = None auth = self._load_json('auth.json') self._bot = Bot(token=auth['token'], request=request.Request( proxy_url=auth['request_kwargs']['proxy_url'], urllib3_proxy_kwargs=auth['request_kwargs'] ['urllib3_proxy_kwargs'])) self._bot_last_update = 0 # Set log file as <module name>.log self._log_path = sys._getframe(0).f_code.co_filename.replace( '<', '').replace('>', '') + '.log' # Config if not config: config = {'/start': 1} self._config = config
def __init__(self, bot_timeout=1, event_timeout=1, ip='176.122.25.59', port=12345): """Создать новый сервер событий и ботов управления.чия события Поддерживает только одно событие в один момент времени! bot_timeout - период проверки наличия сообщений боту. event_timeout - период проверки наличия событий. ip - прослушиваемый адрес сервера событий. port - прослушиваемый порт сервера событий.""" self._operators = [] # Load auth settings and create the telegram bot with open('auth.json', 'r', encoding='utf-8') as f: auth = json.loads(f.read()) self._bot = Bot(token=auth['token'], request=request.Request( proxy_url=auth['request_kwargs']['proxy_url'], urllib3_proxy_kwargs=auth['request_kwargs'] ['urllib3_proxy_kwargs'])) self._bot_last_update = 0 self._bot_timeout = bot_timeout # Create the event server self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.bind((ip, port)) self._socket.settimeout(event_timeout) # Set server frequency self._timeout = bot_timeout + event_timeout # Set log file as <module name>.log self._log_path = sys._getframe(0).f_code.co_filename.replace( '<', '').replace('>', '') + '.log' # Set bot messages handlers self._bot_handlers = {} self.handle('/start', self._cmd_start) self.handle('/stop', self._cmd_stop) self.handle('/list', self._cmd_list)
# encoding = utf-8 from telegram import Bot from telegram.utils import request from Bot_Controller import * if __name__ == "__main__": bot_controller = Bot_Controller() if bot_controller.proxy_url == '': proxy = request.Request(con_pool_size=1028) else: proxy = request.Request(proxy_url=bot_controller.proxy_url, con_pool_size=8) bot = Bot(token=bot_controller.token, request=proxy) bot_controller.set_bot(bot) bot_controller.set_tmall_handler() bot_controller.start_polling()