├── requirements.txt ├── settingsmeta.yaml ├── README.md ├── __init__.py └── LICENSE /requirements.txt: -------------------------------------------------------------------------------- 1 | python-telegram-bot>=12.0 2 | pytz>=2020.1 3 | -------------------------------------------------------------------------------- /settingsmeta.yaml: -------------------------------------------------------------------------------- 1 | skillMetadata: 2 | sections: 3 | - name: Description 4 | fields: 5 | - name: Description 6 | type: label 7 | label: Create a Telegram Bot (with BotFather /newbot or /help) and enter the Token here.

Connect up to two users with their Chat ID.

To get the Chat ID go to https://api.telegram.org/bot/getUpdates or fill in the Bot Token below (save) and write anything to your bot, it will give you your Chat ID.

User fields are not used by the skill and exist only to know which Chat ID belongs to which user.

Both Users have access to both devices and bots, but each Mycroft Device needs a unique TelegramBot. It is not possible to have two Mycroft Devices use one TelegramBot

8 | value: "false" 9 | - name: Settings 10 | fields: 11 | - name: MuteIt 12 | type: checkbox 13 | label: Mute answers when sending via Telegram 14 | value: "false" 15 | - name: TeleToken1 16 | type: text 17 | label: Bot Token (mandatory) 18 | value: "" 19 | placeholder: Bot Token 20 | - name: MDevice1 21 | type: text 22 | label: Device Name (case sensitive | mandatory) 23 | value: "" 24 | placeholder: MyCroft Device Name 25 | - name: User1 26 | type: text 27 | label: Primary Username (optional) 28 | value: "" 29 | placeholder: Username for first Chat ID 30 | - name: TeleID1 31 | type: number 32 | label: Primary Chat ID (mandatory) 33 | value: "" 34 | placeholder: Chat ID 35 | - name: Optional second User 36 | fields: 37 | - name: User2 38 | type: text 39 | label: Second Username (optional) 40 | value: "" 41 | placeholder: Username of second Chat ID 42 | - name: TeleID2 43 | type: number 44 | label: Second Chat ID (optional) 45 | value: "" 46 | placeholder: Second Chat ID 47 | - name: Optional second Device 48 | fields: 49 | - name: TeleToken2 50 | type: text 51 | label: Bot Token (optional) 52 | value: "" 53 | placeholder: Bot Token 54 | - name: MDevice2 55 | type: text 56 | label: Device Name (case sensitive | optional) 57 | value: "" 58 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Telegram 2 | A skill to control your Mycroft instance through a TelegramBot. 3 | 4 | ## About 5 | 6 | You need to create a telegram bot (via BotFather) and save the Bot Token, your ChatID and your MyCroft Device name on home.mycroft.ai under skill settings. 7 | You can now commmunicate with your MyCroft Unit via this bot. 8 | 9 | Settings: 10 | - BOT TOKEN (MANDATORY): Your bot token you got from BotFather 11 | - DEVICE NAME (CASE SENSITIVE | MANDATORY): Your Device name you configured on home.mycroft.ai - Devices - Registered Devices 12 | - BOT TOKEN SECOND MYCROFT DEVICE (OPTIONAL): If you have a second Mycroft Device and you want to use this skill with it -> put your second bot token here (it has to be an other bot than the first one because telegram only allows one device to get updates from one bot) 13 | - SECOND MYCROFT DEVICE NAME (IF YOU HAVE A SECOND DEVICE): Your Device name from your second Device you configured on home.mycroft.ai - Devices - Registered Devices 14 | - PRIMARY USERNAME (OPTIONAL): You do not need to put anything here, the skill does not use this field. It is only for yourself to know which Chat ID belongs to whom 15 | - PRIMARY CHAT ID (MANDATORY): You will get your Chat ID from the Telegram-Skill if you have configured BOT TOKEN (first field) and DEVICE NAME, saved and then write anything to the bot. 16 | - SECOND USERNAME (OPTIONAL): For second User if you have one 17 | - SECOND CHAT ID (IF YOU HAVE A SECOND USER): Same as PRIMARY CHAT ID with Telegram-Account of second user 18 | 19 | Detailed HowTo: 20 | 21 | - Install this skill on your Mycroft Device 22 | 23 | - Create a telegram bot: 24 | Open Telegram App on your smartphone, click on the search symbol in the upper right corner
25 | Search for BotFather and click on it
26 | Now type /newbot hit enter
27 | Botfather should reply with: Alright, a new bot. How are we going to call it? please chosse a name for your bot.
28 | Give your bot a displayname like Mycroft
29 | Botfather should reply with: Good. Now let's choose a username for your bot. It must end in bot. Like this, for example: TetrisBot or tetris-bot.
30 | Give your bot unique username like lukesmycroftbot
31 | Botfather should now give you your token for this bot
32 | Save this token and don't post it online or send it to people, safety first!
33 | 34 | Telegram documentation on botfather: https://core.telegram.org/bots#6-botfather 35 | 36 | - Go to home.mycroft.ai - skills and search for the telegram-skills settings 37 | 38 | - Copy/paste your token botfather gave you in the field BOT TOKEN (MANDATORY) 39 | 40 | - Copy/paste your device name from home.mycroft.ai - devices in DEVICE NAME (CASE SENSITIVE | MANDATORY) 41 | 42 | - SAVE and wait till the settings are synced to your Mycroft Unit (or reboot your device to trigger the sync) 43 | 44 | - Open Telegram App on your smartphone and search (upper right corner) for your bot (username or displayname) click on it and write test or hello to your bot 45 | It should respond with: This is your ChatID: YOURCHATID 46 | 47 | - Copy/paste this under PRIMARY CHAT ID (MANDATORY) 48 | 49 | - SAVE and wait till the settings are synced to your Mycroft Unit (or reboot your device to trigger the sync) 50 | 51 | - On every reboot your bot should send you this welcome message: Telegram-Skill on Mycroft Unit YOURUNIT is loaded and ready to use 52 | 53 | ## Credits 54 | Lukas Gangel (@luke5sky) 55 | 56 | 57 | 58 | ## Category 59 | IoT 60 | **Productivity** 61 | 62 | ## Tags 63 | #messenger 64 | #bot 65 | #telegram-bot 66 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Lukas Gangel 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # TODO: Documentation 16 | 17 | 18 | import telegram 19 | from telegram import Update 20 | 21 | from alsaaudio import Mixer 22 | from mycroft.skills.core import MycroftSkill 23 | from mycroft.util.log import LOG 24 | from telegram.ext import Updater, MessageHandler, Filters, CommandHandler 25 | from websocket import create_connection, WebSocket 26 | from mycroft.messagebus.message import Message 27 | from mycroft.api import DeviceApi 28 | from mycroft.audio import wait_while_speaking 29 | from mycroft.util.log import getLogger 30 | 31 | logger = getLogger(__name__) 32 | 33 | speak_tele = 0 34 | loaded = 0 35 | audioinit = 0 36 | 37 | __author__ = 'luke5sky' 38 | 39 | class TelegramSkill(MycroftSkill): 40 | def __init__(self): 41 | super(TelegramSkill, self).__init__(name="TelegramSkill") 42 | 43 | def initialize(self): 44 | # Handling settings changes 45 | self.settings_change_callback = self.on_settings_changed 46 | self.on_settings_changed() 47 | self.add_event('telegram-skill:response', self.sendHandler) 48 | self.add_event('speak', self.responseHandler) 49 | 50 | # Connection to Telegram API 51 | try: 52 | self.telegram_updater = Updater(token=self.bottoken, use_context=True) # get telegram Updates 53 | self.telegram_dispatcher = self.telegram_updater.dispatcher 54 | receive_handler = MessageHandler(Filters.text, self.TelegramMessages) # TODO: Make audio Files as Input possible: Filters.text | Filters.audio 55 | self.telegram_dispatcher.add_handler(receive_handler) 56 | self.telegram_updater.start_polling(clean=True) # start clean and look for messages 57 | wbot = telegram.Bot(token=self.bottoken) 58 | except: 59 | pass 60 | global loaded # get global variable 61 | if loaded == 0: # check if bot has just started 62 | loaded = 1 # make sure that users gets this message only once bot is newly loaded 63 | if self.mute == "false": 64 | msg = "Telegram Skill is loaded" 65 | self.sendMycroftSay(msg) 66 | loadedmessage = "Telegram-Skill on Mycroft Unit \""+ self.UnitName + "\" is loaded and ready to use!" # give User a nice message 67 | try: 68 | wbot.send_message(chat_id=self.user_id1, text=loadedmessage) # send welcome message to user 1 69 | except: 70 | pass 71 | try: 72 | wbot.send_message(chat_id=self.user_id2, text=loadedmessage) # send welcome message to user 2 73 | except: 74 | pass 75 | 76 | def on_settings_changed(self): 77 | global speak_tele 78 | speak_tele = 0 79 | self.telegram_updater = None 80 | self.mute = str(self.settings.get('MuteIt','')) 81 | if (self.mute == 'True') or (self.mute == 'true'): 82 | try: 83 | self.mixer = Mixer() 84 | msg = "Telegram Messages will temporary mute Mycroft" 85 | logger.info(msg) 86 | except: 87 | global audioinit 88 | if audioinit == 0: 89 | audioinit = 1 90 | msg = "There is a problem with alsa audio, mute is not working!" 91 | self.sendMycroftSay(msg) 92 | logger.info("There is a problem with alsaaudio, mute is not working!") 93 | self.mute = 'false' 94 | else: 95 | logger.info("Telegram: Muting is off") 96 | self.mute = "false" 97 | 98 | try: 99 | # Get Bot Token from settings.json 100 | self.UnitName = DeviceApi().get()['name'] 101 | MyCroftDevice1 = self.settings.get('MDevice1','') 102 | MyCroftDevice2 = self.settings.get('MDevice2','') 103 | except: 104 | pass 105 | try: 106 | self.bottoken = "" 107 | if MyCroftDevice1 == self.UnitName: 108 | logger.debug("Found MyCroft Unit 1: " + self.UnitName) 109 | self.bottoken = self.settings.get('TeleToken1', '') 110 | elif MyCroftDevice2 == self.UnitName: 111 | logger.debug("Found MyCroft Unit 2: " + self.UnitName) 112 | self.bottoken = self.settings.get('TeleToken2', '') 113 | else: 114 | msg = ("No or incorrect Device Name specified! Your DeviceName is: " + self.UnitName) 115 | logger.info(msg) 116 | self.sendMycroftSay(msg) 117 | except: 118 | pass 119 | try: 120 | self.user_id1 = self.settings.get('TeleID1', '') 121 | self.user_id2 = self.settings.get('TeleID2', '') 122 | self.chat_whitelist = [self.user_id1,self.user_id2] 123 | except: 124 | pass 125 | 126 | def TelegramMessages(self, update, context): 127 | msg = update.message.text 128 | chat_id_test = update.message.chat_id 129 | self.chat_id = str(update.message.chat_id) 130 | if self.chat_whitelist.count(chat_id_test) > 0 : 131 | global speak_tele 132 | speak_tele = 1 133 | logger.info("Telegram-Message from User: " + msg) 134 | msg = msg.replace('\\', ' ').replace('\"', '\\\"').replace('(', ' ').replace(')', ' ').replace('{', ' ').replace('}', ' ') 135 | msg = msg.casefold() # some skills need lowercase (eg. the cows list) 136 | self.add_event('recognizer_loop:audio_output_start', self.muteHandler) 137 | self.sendMycroftUtt(msg) 138 | else: 139 | logger.info("Chat ID " + self.chat_id + " is not whitelisted, i don't process it") 140 | nowhite = ("This is your ChatID: " + self.chat_id) 141 | context.bot.send_message(chat_id=self.chat_id, text=nowhite) 142 | 143 | def sendMycroftUtt(self, msg): 144 | self.bus.emit(Message('recognizer_loop:utterance',{"utterances": [msg],"lang": self.lang}))#, "session": session_id})) 145 | 146 | def sendMycroftSay(self, msg): 147 | self.bus.emit(Message('speak', {"utterance": msg,"lang": self.lang})) 148 | 149 | def responseHandler(self, message): 150 | global speak_tele 151 | if speak_tele == 1: 152 | speak_tele = 0 153 | response = message.data.get("utterance") 154 | self.bus.emit(Message("telegram-skill:response", {"intent_name": "telegram-response", "utterance": response })) 155 | 156 | def sendHandler(self, message): 157 | sendData = message.data.get("utterance") 158 | logger.info("Sending to Telegram-User: " + sendData ) 159 | sendbot = telegram.Bot(token=self.bottoken) 160 | sendbot.send_message(chat_id=self.chat_id, text=sendData) 161 | 162 | def muteHandler(self, message): 163 | global speak_tele 164 | if (self.mute == 'true') or (self.mute == 'True'): 165 | self.mixer.setmute(1) 166 | wait_while_speaking() 167 | self.mixer.setmute(0) 168 | self.remove_event('recognizer_loop:audio_output_start') 169 | 170 | def shutdown(self): # shutdown routine 171 | if self.telegram_updater is not None: 172 | self.telegram_updater.stop() # will stop update and dispatcher 173 | self.telegram_updater.is_idle = False 174 | global speak_tele 175 | speak_tele = 0 176 | super(TelegramSkill, self).shutdown() 177 | 178 | def stop(self): 179 | global speak_tele 180 | speak_tele = 0 181 | 182 | def create_skill(): 183 | return TelegramSkill() 184 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | 3 | Version 2.0, January 2004 4 | 5 | http://www.apache.org/licenses/ 6 | 7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 8 | 9 | 1. Definitions. 10 | 11 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 16 | 17 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 18 | 19 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 20 | 21 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 22 | 23 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 24 | 25 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 26 | 27 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 28 | 29 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 30 | 31 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 32 | 33 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 34 | 35 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 36 | 37 | You must give any other recipients of the Work or Derivative Works a copy of this License; and 38 | You must cause any modified files to carry prominent notices stating that You changed the files; and 39 | You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 40 | If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 41 | 42 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 43 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 44 | 45 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 46 | 47 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 48 | 49 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 50 | 51 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 52 | 53 | END OF TERMS AND CONDITIONS 54 | 55 | To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. 56 | 57 | Copyright 2018 Lukas Gangel 58 | 59 | Licensed under the Apache License, Version 2.0 (the "License"); 60 | you may not use this file except in compliance with the License. 61 | You may obtain a copy of the License at 62 | 63 | http://www.apache.org/licenses/LICENSE-2.0 64 | 65 | Unless required by applicable law or agreed to in writing, software 66 | distributed under the License is distributed on an "AS IS" BASIS, 67 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 68 | See the License for the specific language governing permissions and 69 | limitations under the License. 70 | --------------------------------------------------------------------------------