Skip to content

Commit

Permalink
Merge pull request #18 from luke5sky/development
Browse files Browse the repository at this point in the history
v1.4
  • Loading branch information
luke5sky authored Oct 15, 2020
2 parents b879e91 + c921c0f commit d4d5833
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 73 deletions.
23 changes: 11 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
# <img src='https://raw.githack.com/FortAwesome/Font-Awesome/master/svgs/brands/telegram-plane.svg' card_color='#0088CC' width='50' height='50' style='vertical-align:bottom'/> Telegram
# <img src='https://raw.githack.com/FortAwesome/Font-Awesome/master/svgs/solid/paper-plane.svg' card_color='#0088CC' width='50' height='50' style='vertical-align:bottom'/> Telegram
A skill to control your Mycroft instance through a TelegramBot.

## About

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.
After this restart your MyCroft Unit.
You can now commmunicate with your MyCroft Unit via this bot.

Settings:
- BOT TOKEN (MANDATORY): Your bot token you got from BotFather
- MYCROFT DEVICE NAME (MANDATORY): Your Device name you configured on home.mycroft.ai - Devices - Registered Devices
- DEVICE NAME (CASE SENSITIVE | MANDATORY): Your Device name you configured on home.mycroft.ai - Devices - Registered Devices
- 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)
- 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
- USERNAME 1 (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
- CHAT ID 1 (MANDATORY): You will get your Chat ID from the Telegram-Skill if you have configured BOT TOKEN (first field) and MYCROFT DEVICE NAME, saved and then write anything to the bot.
- USERNAME 2 (OPTIONAL): For second User if you have one
- CHAT ID 2 (IF YOU HAVE A SECOND USER): Same as CHAT ID 1 with Telegram-Account of second user
- 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
- 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.
- SECOND USERNAME (OPTIONAL): For second User if you have one
- SECOND CHAT ID (IF YOU HAVE A SECOND USER): Same as PRIMARY CHAT ID with Telegram-Account of second user

Detailed HowTo:

Expand All @@ -38,18 +37,18 @@ Telegram documentation on botfather: https://core.telegram.org/bots#6-botfather

- Copy/paste your token botfather gave you in the field BOT TOKEN (MANDATORY)

- Copy/paste your device name from home.mycroft.ai - devices in MYCROFT DEVICE NAME (MANDATORY)
- Copy/paste your device name from home.mycroft.ai - devices in DEVICE NAME (CASE SENSITIVE | MANDATORY)

- SAVE and wait till the settings are synced to your Mycroft Unit (or reboot your device to trigger the sync)

- 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
It should respond with: This is your ChatID: YOURCHATID

- Copy/paste this under CHAT ID 1 (MANDATORY)

- reboot your device to trigger the sync
- Copy/paste this under PRIMARY CHAT ID (MANDATORY)

- Your bot should send you this welcome message: Telegram-Skill on Mycroft Unit YOURUNIT is loaded and ready to use
- SAVE and wait till the settings are synced to your Mycroft Unit (or reboot your device to trigger the sync)

- On every reboot your bot should send you this welcome message: Telegram-Skill on Mycroft Unit YOURUNIT is loaded and ready to use

## Credits
Lukas Gangel (@luke5sky)
Expand Down
117 changes: 62 additions & 55 deletions __init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

speak_tele = 0
loaded = 0
audioinit = 0

__author__ = 'luke5sky'

Expand All @@ -40,44 +41,12 @@ def __init__(self):
super(TelegramSkill, self).__init__(name="TelegramSkill")

def initialize(self):
self.telegram_updater = None
self.mute = str(self.settings.get('MuteIt',''))
if (self.mute == 'True') or (self.mute == 'true'):
try:
self.mixer = Mixer()
msg = "Telegram Messages will temporary Mute Mycroft"
logger.info(msg)
except:
msg = "There is a problem with alsa audio, mute is not working!"
logger.info("There is a problem with alsaaudio, mute is not working!")
self.sendMycroftSay(msg)
self.mute = 'false'
else:
logger.info("Telegram: Muting is off")
self.mute = "false"
# Handling settings changes
self.settings_change_callback = self.on_settings_changed
self.on_settings_changed()
self.add_event('telegram-skill:response', self.sendHandler)
self.add_event('speak', self.responseHandler)
user_id1 = self.settings.get('TeleID1', '')
user_id2 = self.settings.get('TeleID2', '')
#user_id3 = self.settings.get('TeleID3', '') # makes web-settings too crouded
#user_id4 = self.settings.get('TeleID4', '') # makes web-settings too crouded
self.chat_whitelist = [user_id1,user_id2] #,user_id3,user_id4] # makes web-settings too crouded
# Get Bot Token from settings.json
UnitName = DeviceApi().get()['name']
MyCroftDevice1 = self.settings.get('MDevice1','')
MyCroftDevice2 = self.settings.get('MDevice2','')
self.bottoken = ""
if MyCroftDevice1 == UnitName:
logger.debug("Found MyCroft Unit 1: " + UnitName)
self.bottoken = self.settings.get('TeleToken1', '')
elif MyCroftDevice2 == UnitName:
logger.debug("Found MyCroft Unit 2: " + UnitName)
self.bottoken = self.settings.get('TeleToken2', '')
else:
msg = ("No or incorrect Device Name specified! Your DeviceName is: " + UnitName)
logger.info(msg)
self.sendMycroftSay(msg)


# Connection to Telegram API
try:
self.telegram_updater = Updater(token=self.bottoken, use_context=True) # get telegram Updates
Expand All @@ -89,23 +58,71 @@ def initialize(self):
except:
pass
global loaded # get global variable
if loaded == 0: # check if bot is just started
if loaded == 0: # check if bot has just started
loaded = 1 # make sure that users gets this message only once bot is newly loaded
if self.mute == "false":
msg = "Telegram Skill is loaded"
self.sendMycroftSay(msg)
loadedmessage = "Telegram-Skill on Mycroft Unit \""+ UnitName + "\" is loaded and ready to use!" # give User a nice message
loadedmessage = "Telegram-Skill on Mycroft Unit \""+ self.UnitName + "\" is loaded and ready to use!" # give User a nice message
try:
wbot.send_message(chat_id=user_id1, text=loadedmessage) # send welcome message to user 1
wbot.send_message(chat_id=self.user_id1, text=loadedmessage) # send welcome message to user 1
except:
pass
try:
wbot.send_message(chat_id=user_id2, text=loadedmessage) # send welcome message to user 2
wbot.send_message(chat_id=self.user_id2, text=loadedmessage) # send welcome message to user 2
except:
pass
# wbot.send_message(chat_id=user_id1, text=loadedmessage) # send welcome message to user 3
# wbot.send_message(chat_id=user_id1, text=loadedmessage) # send welcome message to user 4

def on_settings_changed(self):
global speak_tele
speak_tele = 0
self.telegram_updater = None
self.mute = str(self.settings.get('MuteIt',''))
if (self.mute == 'True') or (self.mute == 'true'):
try:
self.mixer = Mixer()
msg = "Telegram Messages will temporary mute Mycroft"
logger.info(msg)
except:
global audioinit
if audioinit == 0:
audioinit = 1
msg = "There is a problem with alsa audio, mute is not working!"
self.sendMycroftSay(msg)
logger.info("There is a problem with alsaaudio, mute is not working!")
self.mute = 'false'
else:
logger.info("Telegram: Muting is off")
self.mute = "false"

try:
# Get Bot Token from settings.json
self.UnitName = DeviceApi().get()['name']
MyCroftDevice1 = self.settings.get('MDevice1','')
MyCroftDevice2 = self.settings.get('MDevice2','')
except:
pass
try:
self.bottoken = ""
if MyCroftDevice1 == self.UnitName:
logger.debug("Found MyCroft Unit 1: " + self.UnitName)
self.bottoken = self.settings.get('TeleToken1', '')
elif MyCroftDevice2 == self.UnitName:
logger.debug("Found MyCroft Unit 2: " + self.UnitName)
self.bottoken = self.settings.get('TeleToken2', '')
else:
msg = ("No or incorrect Device Name specified! Your DeviceName is: " + self.UnitName)
logger.info(msg)
self.sendMycroftSay(msg)
except:
pass
try:
self.user_id1 = self.settings.get('TeleID1', '')
self.user_id2 = self.settings.get('TeleID2', '')
self.chat_whitelist = [self.user_id1,self.user_id2]
except:
pass

def TelegramMessages(self, update, context):
msg = update.message.text
chat_id_test = update.message.chat_id
Expand All @@ -117,27 +134,17 @@ def TelegramMessages(self, update, context):
msg = msg.replace('\\', ' ').replace('\"', '\\\"').replace('(', ' ').replace(')', ' ').replace('{', ' ').replace('}', ' ')
msg = msg.casefold() # some skills need lowercase (eg. the cows list)
self.add_event('recognizer_loop:audio_output_start', self.muteHandler)
self.sendMycroftUtt(msg)

self.sendMycroftUtt(msg)
else:
logger.info("Chat ID " + self.chat_id + " is not whitelisted, i don't process it")
nowhite = ("This is your ChatID: " + self.chat_id)
context.bot.send_message(chat_id=self.chat_id, text=nowhite)

def sendMycroftUtt(self, msg):
uri = 'ws://localhost:8181/core'
ws = create_connection(uri)
utt = '{"context": null, "type": "recognizer_loop:utterance", "data": {"lang": "' + self.lang + '", "utterances": ["' + msg + '"]}}'
ws.send(utt)
ws.close()
self.bus.emit(Message('recognizer_loop:utterance',{"utterances": [msg],"lang": self.lang}))#, "session": session_id}))

def sendMycroftSay(self, msg):
uri = 'ws://localhost:8181/core'
ws = create_connection(uri)
msg = "say " + msg
utt = '{"context": null, "type": "recognizer_loop:utterance", "data": {"lang": "' + self.lang + '", "utterances": ["' + msg + '"]}}'
ws.send(utt)
ws.close()
self.bus.emit(Message('speak', {"utterance": msg,"lang": self.lang}))

def responseHandler(self, message):
global speak_tele
Expand Down
12 changes: 6 additions & 6 deletions settingsmeta.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,17 @@ skillMetadata:
placeholder: Bot Token
- name: MDevice1
type: text
label: MyCroft Device Name (mandatory)
label: Device Name (case sensitive | mandatory)
value: ""
placeholder: MyCroft Device Name
- name: User1
type: text
label: First Username (optional)
label: Primary Username (optional)
value: ""
placeholder: Username for first Chat ID
- name: TeleID1
type: number
label: First Chat ID (mandatory)
label: Primary Chat ID (mandatory)
value: ""
placeholder: Chat ID
- name: Optional second User
Expand All @@ -41,17 +41,17 @@ skillMetadata:
placeholder: Username of second Chat ID
- name: TeleID2
type: number
label: Second Chat ID (if you have a second user)
label: Second Chat ID (optional)
value: ""
placeholder: Second Chat ID
- name: Optional second Device
fields:
- name: TeleToken2
type: text
label: Bot Token second Mycroft Device (optional)
label: Bot Token (optional)
value: ""
placeholder: Bot Token
- name: MDevice2
type: text
label: Second MyCroft Device Name (if you have a second device)
label: Device Name (case sensitive | optional)
value: ""

0 comments on commit d4d5833

Please sign in to comment.