def test_published_expired(self, client): """ test bot.get_unread_bulletins return only published bulletins where publish_at <= now < publish_at + expire_hours """ (user, account) = self.create_user_account() dates = (self.utcnow - datetime.timedelta(hours=4), self.utcnow - datetime.timedelta(hours=1), self.utcnow + datetime.timedelta(hours=2)) for i in range(3): bulletin = self.create_bulletin( account, title='bulletin-%d' % i, publish_at=dates[i].strftime('%m/%d/%Y %H:%M'), is_published=True, expire_hours=2) user.read_bulletins = [] user.save() bot = TelegramBot(str(account.id)) bulletins = bot.get_unread_bulletins(user) assert len(bulletins) == 1 assert bulletins[0].title == 'bulletin-1'
def test_start_bulletin_reading_with_bulletin_id(self, client): (_, account) = self.create_user_account() bulletin1 = self.create_bulletin(account, is_published=True) story1 = self.create_story(bulletin1, lead='story1') self.create_fragment_answer(story1, action='n', text='next1') self.create_fragment_paragraph(story1, text='paragraph1') bulletin2 = self.create_bulletin(account, title='bulletin2', is_published=True) story2 = self.create_story(bulletin2, lead='story2') self.create_fragment_answer(story2, action='n', text='next2') self.create_fragment_paragraph(story2, text='paragraph2') bot = TelegramBot(account.id) bot.bot = Mock() chat_user = self.create_chat_user(account) bot.start_bulletin_reading( chat_user, chat_user.chat_id, disable_no_content=True, bulletin_id=bulletin2.id ) chat_user.reload() assert chat_user.current_bulletin == bulletin2 assert chat_user.state == ChatUser.STATE_WAITING_ANSWER
def test_bot_process_user(self, client): (_, account) = self.create_user_account() bot = TelegramBot(account.id) bot.bot = Mock() chat_id = 1234 bot.handle_message(self.get_telegram_message(chat_id=chat_id)) assert ChatUser.objects.count() == 1 chat_user = ChatUser.objects.get(chat_id=chat_id, account_id=account.id) assert chat_user.name == 'John Smith' assert chat_user.state == ChatUser.STATE_INITIAL_STAGE2 assert chat_user.account_id == account
def __init__(self, _connection_string, token, chat_id, proxy, debug): self._vehicle = None self.connection_string = _connection_string # Params of info-messages self.bot = TelegramBot(token, chat_id, proxy, debug, self) self.debug_message = self.bot.debug_message # Params of auto-missions self._mission_created = False self._goto_location = None self._work_alt = 20 self._need_hover = True # Params of states machine self.current_state = States.INIT self.stop_state = False self.next_state = States.IDLE
def main(): rasa_server = "http://127.0.0.1:5005/webhooks/rest/webhook" bot = TelegramBot("1387499885:AAGiqlocFqKvldZtOptrltLbdOWHIAHNlVA") res = bot.get_me() #name = res["result"]["first_name"] print(res) print("Bot Ready...") while True: messages = bot.get_update() if messages: for msg in messages: print(msg.message) print(msg.chat_id) print(msg.user) res = requests.post(rasa_server, json={ "message": msg.message, "sender": msg.chat_id }).json() print(res) if (res): print(res[0]["text"]) bot.send_message(f"{res[0]['text']}", msg.chat_id) print("==" * 5 + "**" + "==" * 5) print(" - - - - - - -") print("") print("- -") time.sleep(1)
def test_bot_blocked_by_user(self, client): (_, account) = self.create_user_account() chat_user = self.create_chat_user(account) # monkey-patch start_next_question method # simulate blocked msg response def mock_switch_next_profile_story(user, chat_id, disable_no_content=False): raise BotWasBlockedError('Forbidden: bot was blocked by the user', 403, { 'error_code': 403, 'ok': False, 'description': 'Forbidden: bot was blocked by the user' } ) bot = TelegramBot(account.id) bot.bot = Mock() bot.switch_next_profile_story = mock_switch_next_profile_story today = datetime.utcnow().date() stats = AccountStats.objects.get(date=today, account=account) assert stats.new_users == 1 assert stats.dropped_users == 0 bot.handle_message(self.get_telegram_message( text=account.welcome_answer_2_option_1) ) stats.reload() chat_user.reload() assert stats.new_users == 1 assert stats.dropped_users == 1 assert chat_user.disabled == 1
def test_new_users_account_stats(self, client): (_, account) = self.create_user_account() bot = TelegramBot(account.id) bot.bot = Mock() today = datetime.utcnow().date() assert AccountStats.objects(date=today, account=account).count() == 0 # new chat user created bot.get_or_create_user(name='test_user', chat_id='1521512') assert AccountStats.objects(date=today, account=account).count() == 1 stats = AccountStats.objects.get(date=today, account=account) assert stats.new_users == 1 # user already exists bot.get_or_create_user(name='test_user', chat_id='1521512') stats.reload() assert AccountStats.objects(date=today, account=account).count() == 1 assert stats.new_users == 1 # new chat user created bot.get_or_create_user(name='test_user2', chat_id='2142141') stats.reload() assert AccountStats.objects(date=today, account=account).count() == 1 assert stats.new_users == 2
def test_bot_conversation(self, client): (_, account) = self.create_user_account() bulletin = self.create_bulletin(account, is_published=True) story = self.create_story(bulletin, lead='IT') self.create_fragment_answer(story, text='ok') self.create_fragment_paragraph(story, text='ML is cool!!!') bot = TelegramBot(account.id) bot.bot = Mock() self.create_chat_user(account) bot.handle_message(self.get_telegram_message(text=account.welcome_answer_2_option_1)) assert bot.bot.sendMessage.call_args[0][1] == 'IT' bot.bot.reset_mock() bot.handle_message(self.get_telegram_message(text='ok')) assert bot.bot.sendMessage.call_args_list[0][0][1] == 'ML is cool!!!' assert bot.bot.sendMessage.call_args_list[1][0][1] == account.up_to_date_message
def test_bot_sending_published_bulletins(self, client): " sending_published_bulletins -> start_bulletin_reading " (_, account) = self.create_user_account() chat_user = self.create_chat_user(account) bot = TelegramBot(account.id) bot.bot = Mock() bot.handle_message(self.get_telegram_message(text=account.welcome_answer_2_option_1)) assert bot.bot.sendMessage.call_args[0][1] == account.up_to_date_message bulletin = self.create_bulletin(account, is_published=True) story = self.create_story(bulletin, lead='start-story') self.create_fragment_answer(story, action='c', text='read it') bot.bot.reset_mock() bot.sending_published_bulletins() assert bot.bot.sendMessage.call_args[0][1] == 'start-story' assert bot.bot.sendMessage.call_args[1]['reply_markup']['keyboard'] == [['read it']] chat_user.reload() chat_user.state == ChatUser.STATE_WAITING_ANSWER
ignored_tags_artist = user.get('ignored-tags', []) size = user.get('size', 30) a = Artist( user['id'], basedir, client, size=size, subdir=user.get('subdir', None), ignored_tags=ignored_tags + ignored_tags_artist, ) artists.append(a) # set bot bot_config = config['bot'] tg_bot = TelegramBot(bot_config['token'], bot_config['chatid']) return (artists, client, username, password, tg_bot) def start(): artists, client, username, password, tg_bot = init() for a in artists: arts = None try: arts = a.download() except errors.BadApiResponse: logging.warning("download failed. wait for 20 seconds, and retry") time.sleep(20)
update.message.reply_text(message) def main(): if not et.login(settings.everytime['id'], settings.everytime['password']): tb.send_message('로그인 실패! 아이디와 비밀번호를 확인해 주세요.') return load_datas() thread_loop = threading.Thread(target=loop) thread_loop.daemon = True thread_loop.start() tb.send_message('로그인 성공! 주기적으로 게시글을 키워드로 감지해 알림을 보내드리도록 하겠습니다.') tb.add_command_handler('help', handle_help) tb.add_command_handler('add', handle_add) tb.add_command_handler('remove', handle_remove) tb.add_command_handler('show', handle_show) tb.start() if __name__ == '__main__': et = Everytime() tb = TelegramBot(settings.telegram_bot['token'], settings.telegram_bot['chat_id']) # Start main()
from flask import Flask, request, jsonify from telegrambot import TelegramBot from config import * from pyngrok import ngrok from util import sess, facts # Iniitialize essentials app = Flask(__name__) bot = TelegramBot(TELEGRAM_INIT_WEBHOOK_URL) @app.route("/webhook", methods=['POST']) def webhook(): """ runs whenever there is a new message on telegram """ req = request.get_json() success = bot.parse_webhook_data(req) return jsonify(success=success) @app.route("/close") def close(): """ Shuts down the flask server """ func = request.environ.get("werkzeug.server.shutdown") if func is not None: func() if __name__ == "__main__": app.run(port=PORT) # Cleanup
def test_bot_poll(self, client): (_, account) = self.create_user_account() bulletin = self.create_bulletin(account, is_published=True) story = self.create_story(bulletin) self.create_fragment_answer(story) poll_1 = self.create_fragment_poll(story, text='poll1') paragraph_1 = self.create_fragment_paragraph(story, text='paragraph1') poll_2 = self.create_fragment_poll(story, text='poll2') paragraph_2 = self.create_fragment_paragraph(story, text='paragraph2') self.create_fragment_answer(story, text='finish answer') bot = TelegramBot(account.id) bot.bot = Mock() self.create_chat_user(account) bot.handle_message(self.get_telegram_message(text=account.welcome_answer_2_option_1)) assert bot.bot.sendMessage.call_args[0][1] == 'lead1' bot.bot.reset_mock() bot.handle_message(self.get_telegram_message(text='continue')) assert bot.bot.sendMessage.call_args_list[0][0][1] == 'poll1' assert bot.bot.sendMessage.call_args_list[0][1]['reply_markup'][0][0][0][0] == 'answer1' assert bot.bot.sendMessage.call_args_list[0][1]['reply_markup'][0][1][0][0] == 'answer2' answer1_poll1 = PollQuestions.objects.get(fragment=poll_1, text='answer1') # user sent custom message, poll must be resent bot.bot.reset_mock() bot.handle_message(self.get_telegram_message(text='say something')) print(bot.bot.sendMessage.call_args_list) assert bot.bot.sendMessage.call_args_list[0][0][1] == 'poll1' assert bot.bot.sendMessage.call_args_list[0][1]['reply_markup'][0][0][0][0] == 'answer1' assert bot.bot.sendMessage.call_args_list[0][1]['reply_markup'][0][1][0][0] == 'answer2' data = str(poll_1.id) + ',' + str(answer1_poll1.id) bot.bot.reset_mock() bot.handle_callback_query(self.get_telegram_callback_query(data=data)) answer1_poll1.reload() assert self.default_chat_id in answer1_poll1.users assert self.default_chat_id not in PollQuestions.objects.get(fragment=poll_1, text='answer2').users # send paragraph#1 and poll#2 after poll was answered answer2_poll2 = PollQuestions.objects.get(fragment=poll_2, text='answer2') assert bot.bot.sendMessage.call_args_list[0][0][1] == 'paragraph1' assert bot.bot.sendMessage.call_args_list[1][0][1] == 'poll2' assert bot.bot.sendMessage.call_args_list[1][1]['reply_markup'][0][0][0][0] == 'answer1' assert bot.bot.sendMessage.call_args_list[1][1]['reply_markup'][0][1][0][0] == 'answer2' data = str(poll_2.id) + ',' + str(answer2_poll2.id) bot.bot.reset_mock() bot.handle_callback_query(self.get_telegram_callback_query(data=data)) # send paragraph2 and answer after poll assert bot.bot.sendMessage.call_args_list[0][0][1] == 'paragraph2' assert 'finish answer' in bot.bot.sendMessage.call_args[1]['reply_markup']['keyboard'][0] bot.bot.reset_mock() bot.handle_message(self.get_telegram_message(text='finish answer')) assert bot.bot.sendMessage.call_args_list[0][0][1] == 'You are up to date!' answer2_poll2.reload() assert self.default_chat_id in answer2_poll2.users assert self.default_chat_id not in PollQuestions.objects.get(fragment=poll_2, text='answer1').users
def __init__(self, token, channel, nickname, server, port=6667): irc.bot.SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname) self.channel = channel self.telegram = TelegramBot(token, self)
def test_bot_init_conversation(self, client): (_, account) = self.create_user_account() bot = TelegramBot(account.id) bot.bot = Mock() chat_id = 1234 bot.handle_message(self.get_telegram_message(chat_id=chat_id)) sendMessage_args = bot.bot.sendMessage.call_args_list assert sendMessage_args[0][0] == (chat_id, account.welcome_message_1) assert sendMessage_args[1][0][1] == account.welcome_message_2 assert sendMessage_args[1][1]['reply_markup']['keyboard'] == [['Answer 1']] bot.bot.reset_mock() bot.handle_message(self.get_telegram_message(chat_id=chat_id)) sendMessage_args = bot.bot.sendMessage.call_args assert sendMessage_args[0][1] == account.welcome_message_3 assert sendMessage_args[1]['reply_markup']['keyboard'][0][0] == account.welcome_answer_2_option_1 assert sendMessage_args[1]['reply_markup']['keyboard'][0][1] == account.welcome_answer_2_option_2 bot.bot.reset_mock() bot.handle_message(self.get_telegram_message(text='wrong', chat_id=chat_id)) assert bot.bot.method_calls == [] bot.bot.reset_mock() msg = self.get_telegram_message(account.welcome_answer_2_option_1, chat_id=chat_id) bot.handle_message(msg) assert bot.bot.sendMessage.call_args[0][1] == account.up_to_date_message assert bot.bot.sendMessage.call_args[1]['reply_markup']['hide_keyboard'] == True
def test_account_stats(self, client): def upd_enabled_users(): AccountStats.update_enabled_users(Account.objects()) (_, account) = self.create_user_account() upd_enabled_users() bot = TelegramBot(account.id) bot.bot = Mock() # testing enabled_users stats = AccountStats.objects().first() assert stats.enabled_users == 0 assert stats.date.date() == datetime.utcnow().date() assert stats.account == account # testing active_users, new_users chat_user = self.create_chat_user(account) upd_enabled_users() stats.reload() assert stats.enabled_users == 1 assert stats.active_users == 1 assert stats.new_users == 1 assert stats.date.date() == datetime.utcnow().date() assert stats.account == account # testing messages_received bot.handle_message(self.get_telegram_message(text='hi')) bot.handle_message(self.get_telegram_message(text='hi')) bot.handle_message(self.get_telegram_message(text='hi')) stats.reload() assert stats.enabled_users == 1 assert stats.active_users == 1 assert stats.new_users == 1 assert stats.messages_received == 3 # testing dropped_users chat_user.disabled = 1 chat_user.save() stats.reload() assert stats.dropped_users == 1 # test with 2 differrent accounts self.register_data['email'] = '*****@*****.**' (_, account2) = self.create_user_account() self.default_chat_id = 56789 chat_user2 = self.create_chat_user(account2) upd_enabled_users() stats2 = AccountStats.objects.get(account=account2) stats.reload() assert stats.enabled_users == 0 assert stats.active_users == 1 assert stats.new_users == 1 assert stats.messages_received == 3 assert stats.dropped_users == 1 assert stats2.enabled_users == 1 assert stats2.active_users == 1 assert stats2.new_users == 1 assert stats2.messages_received == 0 bot2 = TelegramBot(account2.id) bot2.bot = Mock() bot2.handle_message(self.get_telegram_message( text='hi', chat_id=self.default_chat_id )) stats2.reload() assert stats2.messages_received == 1 # test if stats removed with account account.delete() assert AccountStats.objects(account=account).count() == 0
def test_bot_new_questions(self, client): (_, account) = self.create_user_account() chat_user = self.create_chat_user(account) bot = TelegramBot(account.id) bot.bot = Mock() # finishing onboarding process chat_user.state = ChatUser.STATE_WAITING_READY bot.handle_message( self.get_telegram_message( text=account.welcome_answer_2_option_1 ) ) attr1 = self.create_chat_user_attribute(account, 'attr1', 'int', 'bars', []) story1 = self.create_profile_story('story#1', account) question1 = self.create_question_fragment(attr1, 'question#1', story1) self.add_question_fragment(story1, question1) # question_1 should not be sended # only when UP_TO_DATE reached bot.handle_message( self.get_telegram_message(text='hello') ) chat_user.reload() assert chat_user.onboarding == False assert chat_user.current_profile_story == None assert chat_user.state == ChatUser.STATE_READY_RECEIVED left_no_content_msgs = QUESTION_INTERVAL -\ chat_user.up_to_date_counter # receive QUESTION_INTERVAL no content msgs for i in range(left_no_content_msgs): bot.handle_message(self.get_telegram_message(text='hello')) chat_user.reload() assert chat_user.current_profile_story == None assert chat_user.state == ChatUser.STATE_READY_RECEIVED assert len(chat_user.question_answers) == 0 bot.handle_message(self.get_telegram_message(text='hello')) bot.handle_message(self.get_telegram_message(text='continue')) chat_user.reload() # question_1 sended assert chat_user.onboarding == False assert chat_user.current_profile_story == story1 assert chat_user.state == ChatUser.STATE_WAITING_PROFILE_QUESTION
def test_bot_sending_published_bulletins2(self, client): " sending_published_bulletins -> switch_next_bulletin " (_, account) = self.create_user_account() bulletin1 = self.create_bulletin(account, title='bulletin1', is_published=True) story1 = self.create_story(bulletin1, lead='story1') self.create_fragment_answer(story1, action='n', text='next') self.create_fragment_paragraph(story1, text='paragraph1') story2 = self.create_story(bulletin1, lead='story2') self.create_fragment_answer(story2, action='n', text='next') self.create_fragment_paragraph(story2, text='paragraph2') bulletin2 = self.create_bulletin(account, title='bulletin2', is_published=True) story3 = self.create_story(bulletin2, lead='story3') self.create_fragment_answer(story3, action='n', text='next') self.create_fragment_paragraph(story3, text='paragraph3') self.create_chat_user(account) bot = TelegramBot(account.id) bot.bot = Mock() bot.handle_message(self.get_telegram_message(text=account.welcome_answer_2_option_1)) assert bot.bot.sendMessage.call_args[0][1] == 'story1' bot.bot.reset_mock() bot.sending_published_bulletins() assert bot.bot.sendMessage.call_args is None bot.sending_published_bulletins() assert bot.bot.sendMessage.call_args is None bot.sending_published_bulletins() assert bot.bot.sendMessage.call_args is None bot.sending_published_bulletins() assert bot.bot.sendMessage.call_args[0][1] == 'story3'
def test_bot_profile_story_questions(self, client): (_, account) = self.create_user_account() attr1 = self.create_chat_user_attribute( account, 'attr1', 'text', 'bars', [ {'text': 'opt1', 'value': 'val1'}, {'text': 'opt2', 'value': 'val2'} ] ) attr2 = self.create_chat_user_attribute(account, 'attr1', 'int', 'bars', []) story1 = self.create_profile_story('story#1', account, active=False) question1 = self.create_question_fragment(attr1, 'question#1', story1) self.add_question_fragment(story1, question1) story2 = self.create_profile_story('story#2', account) question2 = self.create_question_fragment(attr2, 'question#2', story2) self.add_question_fragment(story2, question2) story3 = self.create_profile_story('story#3', account) question3 = self.create_question_fragment(attr1, 'question#3', story3) self.add_question_fragment(story3, question3) story4 = self.create_profile_story('story#4', account) question4 = self.create_question_fragment(attr2, 'question#4', story4) self.add_question_fragment(story4, question4) bulletin = self.create_bulletin(account, is_published=True) story = self.create_story(bulletin) self.create_fragment_answer(story, action='c', text='continue') self.create_fragment_paragraph(story) chat_user = self.create_chat_user(account) bot = TelegramBot(account.id) bot.bot = Mock() # finishing onboarding process and send 1st question chat_user.state = ChatUser.STATE_WAITING_READY bot.handle_message( self.get_telegram_message( text=account.welcome_answer_2_option_1 ) ) # story2 sended chat_user.reload() assert chat_user.onboarding == True assert chat_user.current_profile_story == story2 assert chat_user.state == ChatUser.STATE_WAITING_PROFILE_ANSWER # select continue story2 bot.handle_message(self.get_telegram_message(text='continue')) chat_user.reload() assert chat_user.state == ChatUser.STATE_WAITING_PROFILE_QUESTION # answer question2 bot.handle_message(self.get_telegram_message(text='val3')) chat_user.reload() # answer not int type, send current question again assert chat_user.current_profile_story == story2 assert chat_user.state == ChatUser.STATE_WAITING_PROFILE_QUESTION assert len(chat_user.question_answers) == 0 # answer question2, and story2 sended bot.handle_message(self.get_telegram_message(text='10')) # select continue story3 bot.handle_message(self.get_telegram_message(text='continue')) chat_user.reload() assert chat_user.onboarding == True assert chat_user.current_profile_story == story3 assert chat_user.current_profile_fragment_order == 3 assert chat_user.state == ChatUser.STATE_WAITING_PROFILE_QUESTION assert question2 in [answer.question for answer in chat_user.question_answers] assert len(chat_user.question_answers) == 1 # answer question3 bot.handle_message(self.get_telegram_message(text='opt3')) chat_user.reload() # answer not in options, send current question again assert chat_user.current_profile_story == story3 assert chat_user.current_profile_fragment_order == 3 assert chat_user.state == ChatUser.STATE_WAITING_PROFILE_QUESTION assert len(chat_user.question_answers) == 1 # answer question3, and story4 sended bot.handle_message(self.get_telegram_message(text='opt2')) # select continue story4 bot.handle_message(self.get_telegram_message(text='continue')) chat_user.reload() assert chat_user.current_profile_story == story4 assert chat_user.current_profile_fragment_order == 3 assert chat_user.state == ChatUser.STATE_WAITING_PROFILE_QUESTION assert question3 in [answer.question for answer in chat_user.question_answers] assert len(chat_user.question_answers) == 2 # answer question4 # bulletin sended after onboarding questions bot.handle_message(self.get_telegram_message(text='20')) chat_user.reload() assert chat_user.onboarding == False assert chat_user.current_bulletin == bulletin assert not chat_user.current_profile_story assert chat_user.state == ChatUser.STATE_WAITING_ANSWER assert question4 in [answer.question for answer in chat_user.question_answers] assert len(chat_user.question_answers) == 3 bot.handle_message(self.get_telegram_message(text='continue')) chat_user.reload() assert not chat_user.current_bulletin assert chat_user.state == ChatUser.STATE_READY_RECEIVED story1.active = True story1.save() left_no_content_msgs = QUESTION_INTERVAL -\ chat_user.up_to_date_counter # receive QUESTION_INTERVAL no content msgs for i in range(left_no_content_msgs): bot.handle_message(self.get_telegram_message(text='hello')) chat_user.reload() assert not chat_user.current_profile_story assert chat_user.state == ChatUser.STATE_READY_RECEIVED assert len(chat_user.question_answers) == 3 # story1 sended bot.handle_message(self.get_telegram_message(text='hello')) bot.handle_message(self.get_telegram_message(text='continue')) chat_user.reload() # question1 sended assert chat_user.onboarding == False assert chat_user.current_profile_story == story1 assert chat_user.state == ChatUser.STATE_WAITING_PROFILE_QUESTION assert len(chat_user.question_answers) == 3 assert chat_user.up_to_date_counter == 0 # answer question1 bot.handle_message(self.get_telegram_message(text='opt1')) chat_user.reload() assert not chat_user.current_profile_story assert chat_user.state == ChatUser.STATE_READY_RECEIVED assert question1 in [answer.question for answer in chat_user.question_answers] assert len(chat_user.question_answers) == 4
from flask import Flask, request, jsonify from telegrambot import TelegramBot from config import TELEGRAM_INIT_WEBHOOK_URL import requests import threading wrapper = Flask(__name__) # the post message requests.get(TELEGRAM_INIT_WEBHOOK_URL) bot = TelegramBot() @wrapper.route('/webhook', methods=['POST']) def index(): req = request.get_json() bot.parse_webhook_data(req) success = bot.replay() return jsonify(success=success) if __name__ == '__main__': # auto massaging thread t1 = threading.Thread(target=bot.auto_send, daemon=True).start() print("start listening") # the main thread wrapper.run(port=2000)
def test_bot_answers_next(self, client): (_, account) = self.create_user_account() bulletin1 = self.create_bulletin(account, is_published=True) story1 = self.create_story(bulletin1, lead='story1') self.create_fragment_answer(story1, action='n', text='next1') self.create_fragment_paragraph(story1, text='paragraph1') story2 = self.create_story(bulletin1, lead='story2') self.create_fragment_answer(story2, action='n', text='next2') self.create_fragment_paragraph(story2, text='paragraph2') story3 = self.create_story(self.create_bulletin(account, is_published=True), lead='story3') self.create_fragment_answer(story3, action='n', text='next3') self.create_fragment_paragraph(story3, text='paragraph3') bot = TelegramBot(account.id) bot.bot = Mock() self.create_chat_user(account) bot.handle_message(self.get_telegram_message(text=account.welcome_answer_2_option_1)) assert bot.bot.sendMessage.call_args[0][1] == 'story1' bot.bot.reset_mock() bot.handle_message(self.get_telegram_message(text='next')) assert bot.bot.sendMessage.call_args[0][1] == account.unknown_answer_message bot.bot.reset_mock() bot.handle_message(self.get_telegram_message(text='next1')) assert bot.bot.sendMessage.call_args[0][1] == 'story2' bot.bot.reset_mock() bot.handle_message(self.get_telegram_message(text='next')) assert bot.bot.sendMessage.call_args[0][1] == account.unknown_answer_message bot.bot.reset_mock() bot.handle_message(self.get_telegram_message(text='next2')) assert bot.bot.sendMessage.call_args[0][1] == 'story3' bot.bot.reset_mock() bot.handle_message(self.get_telegram_message(text='next')) assert bot.bot.sendMessage.call_args[0][1] == account.unknown_answer_message bot.bot.reset_mock() bot.handle_message(self.get_telegram_message(text='next3')) assert bot.bot.sendMessage.call_args[0][1] == account.up_to_date_message
self.itemy.pop(1) if len(self.itemx)> 6: ret = self.patterndb.check(self.itemy, self.itemx) if ret: print ret self.telecobj.sendmsg(text = "New pattern found in BTC ") def connect_handler(self, data): channel = self.pusher.subscribe('live_trades') channel.bind('trade', self.callback) if __name__ == "__main__": #Message bot handler bot = TelegramBot(token = "", dbname = "btc_telegram.db") bot.start() # Add a logging handler so we can see the raw communication data import logging root = logging.getLogger() root.setLevel(logging.INFO) ch = logging.StreamHandler(sys.stdout) root.addHandler(ch) pu = Pusher() try: while True: time.sleep(1) except:
def test_bot_conversation2(self, client): (_, account) = self.create_user_account() bulletin = self.create_bulletin(account, is_published=True) story1 = self.create_story(bulletin, lead='story1') self.create_fragment_answer(story1, action='c', text='continue') self.create_fragment_answer(story1, action='n', text='next') poll = self.create_fragment_poll(story1, text='poll') self.create_fragment_paragraph(story1, text='paragraph1') story2 = self.create_story(bulletin, lead='story2') self.create_fragment_answer(story2, action='c', text='continue') self.create_fragment_answer(story2, action='n', text='next') self.create_fragment_paragraph(story2, text='paragraph2') self.create_fragment_answer(story2, action='c', text='continue') self.create_fragment_answer(story2, action='n', text='next') bot = TelegramBot(account.id) bot.bot = Mock() self.create_chat_user(account) bot.handle_message(self.get_telegram_message(text=account.welcome_answer_2_option_1)) assert bot.bot.sendMessage.call_args[0][1] == 'story1' bot.bot.reset_mock() bot.handle_message(self.get_telegram_message(text='continue')) assert bot.bot.sendMessage.call_args[0][1] == 'poll' answer1_poll = PollQuestions.objects.get(fragment=poll, text='answer1') data = str(poll.id) + ',' + str(answer1_poll.id) bot.bot.reset_mock() bot.handle_callback_query(self.get_telegram_callback_query(data=data)) assert bot.bot.sendMessage.call_args_list[0][0][1] == 'paragraph1' assert bot.bot.sendMessage.call_args_list[1][0][1] == 'story2' bot.bot.reset_mock() bot.handle_message(self.get_telegram_message(text='continue')) assert bot.bot.sendMessage.call_args[0][1] == 'paragraph2'
class Autocopter(object): """ This class consists of logic for states (methods 'do_*' & dependencies) and method 'new_command' """ def __init__(self, _connection_string, token, chat_id, proxy, debug): self._vehicle = None self.connection_string = _connection_string # Params of info-messages self.bot = TelegramBot(token, chat_id, proxy, debug, self) self.debug_message = self.bot.debug_message # Params of auto-missions self._mission_created = False self._goto_location = None self._work_alt = 20 self._need_hover = True # Params of states machine self.current_state = States.INIT self.stop_state = False self.next_state = States.IDLE def _create_mission(self, lat, lon): self._mission_created = False # exeption https://pythonworld.ru/tipy-dannyx-v-python/isklyucheniya-v-python-konstrukciya-try-except-dlya-obrabotki-isklyuchenij.html try: self._goto_location = LocationGlobalRelative( lat, lon, self._work_alt) # print 'Create a new mission (for current location)' self._adds_square_mission( self._vehicle.location.global_relative_frame, 6) self._mission_created = True return "Миссия успешно построена!" except Exception as ex: self._mission_created = False return "Произошла ошибка при построении миссии\n" + ex.message + "\n" + traceback.format_exc( ) finally: pass def new_state(self, new_state): self.stop_state = True self.next_state = new_state @property def get_location(): return self._vehicle.location.global_frame.lat, self._vehicle.location.global_frame.lon @property def _status_of_connect(self): if self._vehicle != None: return True else: raise Exception("Не удалось подключиться к APM") def disconnect(self): ''' Close vehicle object before exiting script :return: ''' if self._vehicle != None: self._vehicle.close() print "Successful disconnect APM" @property def get_status(self): buf = "\nGPS: %s" % self._vehicle.gps_0 + \ "\nBattery: %s" % self._vehicle.battery + \ "\nLast Heartbeat: %s" % self._vehicle.last_heartbeat + \ "\nIs Armable?: %s" % self._is_armable + \ "\nSystem status: %s" % self._vehicle.system_status.state + \ "\nMode: %s" % self._vehicle.mode.name + \ "\nGlobal Location: %s" % self._vehicle.location.global_frame + \ "\nGlobal Relative Location: %s" % self._vehicle.location.global_relative_frame + \ "\nLocal Location: %s" % self._vehicle.location.local_frame + \ "\nAttitude: %s" % self._vehicle.attitude + \ "\nHeading: %s" % self._vehicle.heading + \ "\nGroundspeed: %s" % self._vehicle.groundspeed + \ "\nAirspeed: %s" % self._vehicle.airspeed return buf @property def _distance_to_current_waypoint(self): """ Gets distance in metres to the current waypoint. It returns None for the first waypoint (Home location). """ nextwaypoint = self._vehicle.commands.next if nextwaypoint == 0: return None missionitem = self._vehicle.commands[nextwaypoint - 1] # commands are zero indexed lat = missionitem.x lon = missionitem.y alt = missionitem.z targetWaypointLocation = LocationGlobalRelative(lat, lon, alt) distancetopoint = get_distance_metres( self._vehicle.location.global_frame, targetWaypointLocation) return distancetopoint def download_mission(self): """ Download the current mission from the vehicle. """ cmds = self._vehicle.commands cmds.download() cmds.wait_ready() # wait until download is complete. def _adds_square_mission(self, aLocation, aSize): """ Adds a takeoff command and four waypoint commands to the current mission. The waypoints are positioned to form a square of side length 2*aSize around the specified LocationGlobal (aLocation). The function assumes vehicle.commands matches the vehicle mission state (you must have called download at least once in the session and after clearing the mission) """ cmds = self._vehicle.commands print "Clear any existing commands" cmds.clear() print "Define/add new commands." # Add new commands. The meaning/order of the parameters is documented in the Command class. # Add MAV_CMD_NAV_TAKEOFF command. This is ignored if the vehicle is already in the air. cmds.add( Command(0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 0, 0, 0, 0, 0, 0, 0, 0, 10)) # Define the four MAV_CMD_NAV_WAYPOINT locations and add the commands point1 = get_location_metres(aLocation, aSize, -aSize) point2 = get_location_metres(aLocation, aSize, aSize) point3 = get_location_metres(aLocation, -aSize, aSize) point4 = get_location_metres(aLocation, -aSize, -aSize) cmds.add( Command(0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, point1.lat, point1.lon, 11)) cmds.add( Command(0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, point2.lat, point2.lon, 12)) cmds.add( Command(0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, point3.lat, point3.lon, 13)) cmds.add( Command(0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, point4.lat, point4.lon, 14)) # add dummy waypoint "5" at point 4 (lets us know when have reached destination) cmds.add( Command(0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, point4.lat, point4.lon, 14)) print "Upload new commands to vehicle" cmds.upload() @property def onLand(self): return self._vehicle.system_status.state == 'STANDBY' def do_INIT(self): self.current_state = States.INIT wait_internet() print "Try send message..." self.debug_message("Autocopter is online: %s" % get_ip()) self.debug_message("STATE = %s" % self.current_state) self.bot.start_handler() time.sleep( 1.5) # время на ответ сообщений пришедших в выключенный период while True: try: self.debug_message("Connecting to APM ...") # http://python.dronekit.io/automodule.html#dronekit.connect # функция долгая (пишет через функцию status_printer) self._vehicle = connect(self.connection_string, wait_ready=True, status_printer=self.debug_message) if self._status_of_connect: self.debug_message("Connect successful!") next_state = States.IDLE self.debug_message("Успешное завершение состояния %s" % self.current_state + " переключение в состояние %s" % next_state) self.current_state = next_state break except Exception as ex: #self.debug_message("Ошибка в состоянии %s" % self.current_state + ":\n" + ex.message + "\n" + traceback.format_exc() + "\n") self.debug_message("Connection failed!") self.debug_message("Timeout 10s") time.sleep(10) def do_LAND(self): self.current_state = States.LAND self.debug_message('STATE = ' + self.current_state) self.stop_state = False self.next_state = States.IDLE # http://ardupilot.org/copter/docs/land-mode.html self._vehicle.mode = VehicleMode("LAND") while not self.onLand: if not self.stop_state: #self.debug_message('Waiting for ' + self.current_state) time.sleep(1) else: self.debug_message( "Прерывание состояния %s" % self.current_state + " переключение в состояние %s" % self.next_state) return self.next_state self.debug_message("Успешное завершение состояния %s" % self.current_state + " переключение в состояние %s" % self.next_state) return self.next_state def do_IDLE(self): self.current_state = States.IDLE self.debug_message("STATE = %s" % self.current_state) self.stop_state = False self.next_state = States.IDLE # http://ardupilot.org/copter/docs/ac2_guidedmode.html # http://python.dronekit.io/examples/guided-set-speed-yaw-demo.html self._vehicle.armed = False self._vehicle.mode = VehicleMode("GUIDED") while True: if not self.stop_state: #self.debug_message('I\'m in '+self.current_state) time.sleep(1) else: self.debug_message( "Прерывание состояния %s" % self.current_state + " переключение в состояние %s" % self.next_state) return self.next_state self.debug_message("Успешное завершение состояния %s" % self.current_state + " переключение в состояние %s" % self.next_state) return self.next_state def _simple_goto_wrapper(self, lat, lon, alt=20, groundspeed=7.5): # Задаем координаты нужной точки a_location = LocationGlobalRelative(lat, lon, alt) # полетели self._vehicle.simple_goto(a_location) # Путевая скорость, м/с self._vehicle.groundspeed = groundspeed def do_HOVER(self): self.current_state = States.HOVER self.debug_message("STATE = %s" % self.current_state) self.stop_state = False self.next_state = States.HOVER self._vehicle.mode = VehicleMode("GUIDED") if self._need_hover: self._simple_goto_wrapper( self._vehicle.location.global_relative_frame.lat, self._vehicle.location.global_relative_frame.lon, self._vehicle.location.global_relative_frame.alt) self._need_hover = True #сброс while True: if not self.stop_state: #self.debug_message('I\'m in '+self.current_state) time.sleep(1) else: self.debug_message( "Прерывание состояния %s" % self.current_state + " переключение в состояние %s" % self.next_state) return self.next_state self.debug_message("Успешное завершение состояния %s" % self.current_state + " переключение в состояние %s" % self.next_state) return self.next_state def do_RTL(self): self.current_state = States.RTL self.debug_message("STATE = %s" % self.current_state) self.stop_state = False self.next_state = States.IDLE # http://ardupilot.org/copter/docs/rtl-mode.html self._vehicle.mode = VehicleMode("RTL") while not self.onLand: if not self.stop_state: #self.debug_message('Waiting for ' + self.current_state) time.sleep(1) else: self.debug_message( "Прерывание состояния %s" % self.current_state + " переключение в состояние %s" % self.next_state) return self.next_state self.debug_message("Успешное завершение состояния %s" % self.current_state + " переключение в состояние %s" % self.next_state) return self.next_state @property def _is_armable(self): """ Returns `True` if the vehicle is ready to arm, false otherwise (``Boolean``). This attribute wraps a number of pre-arm checks, ensuring that the vehicle has booted, has a good GPS fix, and that the EKF pre-arm is complete. """ # check that mode is not INITIALSING # check that we have a GPS fix # check that EKF pre-arm is complete return self._vehicle.mode != 'INITIALISING' and self._vehicle.gps_0.fix_type > 1 # and self.vehicle._ekf_predposhorizabs #отключена проверка ekf def do_TAKEOFF(self): aTargetAltitude = self._work_alt self.current_state = States.TAKEOFF self.debug_message("STATE = %s" % self.current_state) self.stop_state = False self.next_state = States.GOTO """ Arms vehicle and fly to aTargetAltitude. """ self.debug_message("Basic pre-arm checks") # Don't let the user try to arm until autopilot is ready self.debug_message("Waiting for vehicle to initialise...") while not self._is_armable: #проверка не дронкита, а собственная if not self.stop_state: #self.debug_message('Waiting for ' + self.current_state) #self.debug_message('Waiting for vehicle to initialise...') time.sleep(1) else: self.debug_message( "Прерывание состояния %s" % self.current_state + " переключение в состояние %s" % self.next_state) self.debug_message("Stopping takeoff on pre-arm!") return self.next_state # Copter should arm in GUIDED mode self._vehicle.mode = VehicleMode("GUIDED") self.debug_message("Arming motors") self._vehicle.armed = True while not self._vehicle.armed: if not self.stop_state: #self.debug_message('Waiting for ' + self.current_state) #self.debug_message('Waiting for arming...') time.sleep(1) else: self.debug_message( "Прерывание состояния %s" % self.current_state + " переключение в состояние %s" % self.next_state) self.debug_message("Stopping takeoff on arm!") return self.next_state self.debug_message("Taking off!") self._vehicle.simple_takeoff( aTargetAltitude) # Take off to target altitude # Wait until the vehicle reaches a safe height before processing the goto (otherwise the command # after Vehicle.simple_takeoff will execute immediately). while self._vehicle.location.global_relative_frame.alt < aTargetAltitude * 0.95: # Trigger just below target alt. if not self.stop_state: #self.debug_message('Waiting for ' + self.current_state) self.debug_message( "Altitude: %s" % self._vehicle.location.global_relative_frame.alt) time.sleep(1) else: self.debug_message( "Прерывание состояния %s" % self.current_state + " переключение в состояние %s" % self.next_state) self.debug_message("Stopping takeoff on fly!") return self.next_state self.debug_message("Успешное завершение состояния %s" % self.current_state + " переключение в состояние %s" % self.next_state) self._need_hover = False return self.next_state def _is_arrived(self, lat, lon, alt, precision=0.3): # функция взята из https://habrahabr.ru/post/281591/ # текущая позиция veh_loc = self._vehicle.location.global_relative_frame # получаем данные в метрах diff_lat_m = (lat - veh_loc.lat) * 1.113195e5 diff_lon_m = (lon - veh_loc.lon) * 1.113195e5 diff_alt_m = alt - veh_loc.alt # отклонение dist_xyz = math.sqrt(diff_lat_m**2 + diff_lon_m**2 + diff_alt_m**2) if dist_xyz < precision: #print "Прибыли на место" return True else: #print "Еще не долетели" return False def do_GOTO(self): self.next_state = States.HOVER # должен быть только HOVER if self._mission_created: self.current_state = States.GOTO self.debug_message("STATE = %s" % self.current_state) self.stop_state = False self.next_state = States.HOVER self._vehicle.mode = VehicleMode("GUIDED") self._simple_goto_wrapper(self._goto_location.lat, self._goto_location.lon, self._goto_location.alt) while self._is_arrived(self._goto_location.lat, self._goto_location.lon, self._goto_location.alt): if not self.stop_state: #self.debug_message('I\'m in '+self.current_state) self.debug_message("До точки назначения: " + get_distance_metres( self._goto_location, self._vehicle. location.global_relative_frame) + "м") time.sleep(1) else: self.debug_message( "Прерывание состояния %s" % self.current_state + " переключение в состояние %s" % self.next_state) return self.next_state self.debug_message( "Успешное завершение состояния %s" % self.current_state + " переключение в состояние %s" % self.next_state) self._need_hover = False return self.next_state else: self.debug_message("Ошибка: Создайте миссию заранее! Сейчас %s" % self.current_state + " переключение в состояние %s" % self.next_state) return self.next_state def do_AUTO(self): self.next_state = self.current_state # должен быть только HOVER if self._mission_created: self.current_state = States.AUTO self.debug_message("STATE = %s" % self.current_state) self.stop_state = False self.next_state = States.HOVER self.debug_message("Starting mission") # Reset mission set to first (0) waypoint self._vehicle.commands.next = 0 # Set mode to AUTO to start mission # http://ardupilot.org/copter/docs/auto-mode.html self._vehicle.mode = VehicleMode("AUTO") # Monitor mission. # Demonstrates getting and setting the command number # Uses _distance_to_current_waypoint(), a convenience function for finding the # distance to the next waypoint. while True: if not self.stop_state: nextwaypoint = self._vehicle.commands.next self.debug_message( "Distance to waypoint (%s): %sм" % (nextwaypoint, self._distance_to_current_waypoint)) time.sleep(1) else: self.debug_message( "Прерывание состояния %s" % self.current_state + " переключение в состояние %s" % self.next_state) return self.next_state self.debug_message( "Успешное завершение состояния %s" % self.current_state + " переключение в состояние %s" % self.next_state) # может и не нужна стабилизация но на всякий (вдруг failsafe будет) # self._need_hover = False return self.next_state else: self.debug_message("Ошибка: Создайте миссию заранее! Сейчас %s" % self.current_state + " переключение в состояние %s" % self.next_state) return self.next_state
def test_bot_answers_continue(self, client): (_, account) = self.create_user_account() story = self.create_story(self.create_bulletin(account, is_published=True)) self.create_fragment_answer(story, action='c', text='continue') self.create_fragment_answer(story, action='n', text='next') self.create_fragment_paragraph(story, text='chapter1') self.create_fragment_answer(story, action='c', text='continue2') self.create_fragment_answer(story, action='n', text='next2') self.create_fragment_paragraph(story, text='chapter2') bot = TelegramBot(account.id) bot.bot = Mock() self.create_chat_user(account) bot.handle_message(self.get_telegram_message(text=account.welcome_answer_2_option_1)) assert bot.bot.sendMessage.call_args[0][1] == 'lead1' bot.bot.reset_mock() bot.handle_message(self.get_telegram_message(text='continue')) call = bot.bot.sendMessage.call_args_list[0] assert call[0][1] == 'chapter1' assert call[1]['reply_markup']['keyboard'] == [['continue2'], ['next2']] bot.bot.reset_mock() bot.handle_message(self.get_telegram_message(text='continue')) call = bot.bot.sendMessage.call_args_list[0] assert call[0][1] == account.unknown_answer_message assert call[1]['reply_markup']['keyboard'] == [['continue2'], ['next2']] bot.bot.reset_mock() bot.handle_message(self.get_telegram_message(text='next')) call = bot.bot.sendMessage.call_args_list[0] assert call[0][1] == account.unknown_answer_message assert call[1]['reply_markup']['keyboard'] == [['continue2'], ['next2']] bot.bot.reset_mock() bot.handle_message(self.get_telegram_message(text='continue2')) assert bot.bot.sendMessage.call_args_list[0][0][1] == 'chapter2' assert bot.bot.sendMessage.call_args_list[1][0][1] == account.up_to_date_message
class Bot(irc.bot.SingleServerIRCBot): def __init__(self, token, channel, nickname, server, port=6667): irc.bot.SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname) self.channel = channel self.telegram = TelegramBot(token, self) def on_nicknameinuse(self, c, e): logger.info('nickname already in use, add an underscore') c.nick(c.get_nickname() + "_") def on_welcome(self, c, e): # server welcome logger.info('joining channel: {0:s}'.format(self.channel)) c.join(self.channel) def on_privmsg(self, c, e): logger.debug('on private message, event: ' + str(e)) logger.info('private msg: {0:s}'.format(e.arguments[0])) self.telegram.notify_owner(e.arguments[0]) self.do_command(e, e.arguments[0]) def on_pubmsg(self, c, e): logger.debug('on public message, event: ' + str(e)) nick = e.source.split('!')[0] msg = e.arguments[0] current_time = datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S") logger.info('[{0:s}] <{1:s}> {2:s}'.format(current_time, nick, msg)) self.telegram.send_msg(nick, msg) def on_kick(self, c, e): # arg[0] was kicked by e.source (arg[1]) logger.debug('on kick, event: ' + str(e)) kicked_user = e.arguments[0] kicked_by = self.get_nick(e.source) reason = e.arguments[1] msg = '{0:s} was kicked by {1:s} ({2:s})'.format( kicked_user, kicked_by, reason) logger.info('* ' + msg) self.telegram.send_notification(msg) def on_join(self, c, e): # e.source has joined e.target logger.debug('on join, event: ' + str(e)) joined_user = self.get_nick(e.source) joined_user_id = self.get_id(e.source) channel = e.target.replace('#', '') msg = '{0:s} ({1:s}) has joined {2:s}'.format(joined_user, joined_user_id, channel) logger.info('* ' + msg) # avoid sending telegram users the joined msg when the bot joins the irc channel if joined_user != c.get_nickname(): self.telegram.send_notification(msg) def on_quit(self, c, e): # e.source Quit (arg[0]) logger.debug('on quit, event: ' + str(e)) leaving_user = self.get_nick(e.source) leaving_user_id = self.get_id(e.source) quit_msg = e.arguments[0] msg = '{0:s} ({1:s}) Quit ({2:s})'.format(leaving_user, leaving_user_id, quit_msg) logger.info('* ' + msg) self.telegram.send_notification(msg) def on_part(self, c, e): # e.source has left e.target logger.debug('on part, event: ' + str(e)) leaving_user = self.get_nick(e.source) leaving_user_id = self.get_id(e.source) channel = e.target.replace('#', '') msg = '{0:s} ({1:s}) has left {2:s}'.format(leaving_user, leaving_user_id, channel) logger.info('* ' + msg) self.telegram.send_notification(msg) def on_topic(self, c, e): # e.source sets topic arg[0] logger.debug('on topic, event: ' + str(e)) topic_changer = self.get_nick(e.source) new_topic = e.arguments[0] msg = '{0:s} changes topic to \'{1:s}\''.format( topic_changer, new_topic) logger.info('* ' + msg) self.telegram.send_notification(msg) def on_nick(self, c, e): # e.source is now known as e.target logger.debug('on nick, event: ' + str(e)) nick_changer = self.get_nick(e.source) new_nick = e.target msg = '{0:s} is now known as {1:s}'.format(nick_changer, new_nick) logger.info('* ' + msg) self.telegram.send_notification(msg) def on_mode(self, c, e): # e.source sets mode arg[0] arg[1] logger.debug('on mode, event: ' + str(e)) mode_changer = self.get_nick(e.source) new_mode = ' '.join(e.arguments) msg = '{0:s} sets mode: {1:s}'.format(mode_changer, new_mode) logger.info('* ' + msg) self.telegram.send_notification(msg) def on_action(self, c, e): # no use case for now logger.debug('on action, event: ' + str(e)) pass def do_command(self, e, cmd): nick = e.source.nick c = self.connection if cmd == "disconnect": self.disconnect() elif cmd == "die": self.die() @staticmethod def get_nick(full_id): return full_id.split('!')[0] @staticmethod def get_id(full_id): return full_id.split('!')[1] def get_users(self): logger.debug('getting channel users') users = {} channel_obj = self.channels[self.channel] users['users'] = sorted( set(channel_obj.users()) - set(list(channel_obj.opers()) + list(channel_obj.voiced())), key=self.user_sort_key) users['opers'] = sorted(channel_obj.opers(), key=self.user_sort_key) users['voiced'] = sorted(set(channel_obj.voiced()) - set(channel_obj.opers()), key=self.user_sort_key) return users def user_sort_key(self, user): # TODO fix name ordering return ''.join(c for c in user if c not in '[]{}()<>')
from telegrambot import TelegramBot bot = TelegramBot() bot.start()
from settings import EnvSettings from database import Database from telegrambot import TelegramBot import logging if __name__ == '__main__': try: settings = EnvSettings() db = Database( settings.DB_HOST, settings.DB_NAME, settings.DB_PORT, settings.DB_USER, settings.DB_PASS ) bot = TelegramBot(settings.TOKEN, settings.APP_NAME, settings.PORT, db, settings.IS_PROD) except Exception as e: logging.exception() logging_kwargs = { 'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s', 'level': logging.INFO } logging.basicConfig(**logging_kwargs)
def test_bot_last_message_increment(self, client): (_, account) = self.create_user_account() bulletin = self.create_bulletin(account, is_published=True) story1 = self.create_story(bulletin) self.create_fragment_answer(story1, action='n', text='next') self.create_fragment_answer(story1, action='c', text='continue') self.create_fragment_paragraph(story1) self.create_fragment_answer(story1, action='n', text='next') self.create_fragment_answer(story1, action='c', text='continue') self.create_fragment_paragraph(story1) story2 = self.create_story(bulletin) self.create_fragment_answer(story2, action='n', text='next') self.create_fragment_answer(story2, action='c', text='continue') chat_user = self.create_chat_user(account) last_message = chat_user.last_message bot = TelegramBot(account.id) bot.bot = Mock() def __check(): nonlocal last_message chat_user.reload() assert chat_user.last_message > last_message last_message = chat_user.last_message bot.handle_message(self.get_telegram_message(text=account.welcome_answer_2_option_1)) __check() bot.handle_message(self.get_telegram_message(text='continue')) __check() bot.handle_message(self.get_telegram_message(text='next')) __check() bot.handle_message(self.get_telegram_message(text='continue')) __check()