diff --git a/README.md b/README.md
index 677926a4..7b7e43f4 100644
--- a/README.md
+++ b/README.md
@@ -78,7 +78,7 @@ does not do this automatically.
* [ ] Mentions
* [ ] Images
* [ ] Locations
- * [ ] Stickers (somewhat works through document upload, no preview though)
+ * [ ] Stickers
* [ ] Audio messages
* [ ] Video messages
* [ ] Documents
diff --git a/example-config.yaml b/example-config.yaml
index c9f5e445..a17af508 100644
--- a/example-config.yaml
+++ b/example-config.yaml
@@ -21,6 +21,7 @@ appservice:
id: telegram
# Username of the appservice bot.
bot_username: telegrambot
+ bot_displayname: Mautrix-Telegram Bridge
# Authentication tokens for AS <-> HS communication. Autogenerated; do not modify.
as_token: "This value is generated when generating the registration"
@@ -56,18 +57,9 @@ bridge:
- username
- phoneNumber
- # Bridge command configuration
- commands:
- # The prefix for commands.
- # This is only required in rooms with users more than two users.
- prefix: "!tg"
- # Whether or not to allow management commands in rooms with more than two users.
- # Non-management commands are allowed in portal rooms even if this is false.
- allow_in_groups: false
-
- # Enables the !tg api ... commands for debugging.
- allow_direct_api_calls: false
+ # The prefix for commands. Only required in non-management rooms.
+ command_prefix: "!tg"
# Whitelist of user IDs that are allowed to use this bridge. Leave empty to disable.
# You can enter a domain without the localpart to allow all users from that homeserver to use the bridge.
diff --git a/mautrix_appservice/intent_api.py b/mautrix_appservice/intent_api.py
index f8a15d3d..d1e322a2 100644
--- a/mautrix_appservice/intent_api.py
+++ b/mautrix_appservice/intent_api.py
@@ -51,7 +51,8 @@ class HTTPAPI(MatrixHttpApi):
self.log.debug("%s %s %s", method, path, content)
return super()._send(method, path, content, query_params, headers)
- def create_room(self, alias=None, is_public=False, name=None, topic=None, is_direct=False, invitees=()):
+ def create_room(self, alias=None, is_public=False, name=None, topic=None, is_direct=False,
+ invitees=()):
"""Perform /createRoom.
Args:
alias (str): Optional. The room alias name to set for this room.
@@ -136,17 +137,18 @@ class IntentAPI:
self._ensure_registered()
return self.client.set_display_name(self.mxid, name)
- def create_room(self, alias=None, is_public=False, name=None, topic=None, is_direct=False, invitees=()):
+ def create_room(self, alias=None, is_public=False, name=None, topic=None, is_direct=False,
+ invitees=()):
self._ensure_registered()
return self.client.create_room(alias, is_public, name, topic, is_direct, invitees)
- def send_text(self, room_id, text, html=False, unformatted_text=None, notice=False):
+ def send_text(self, room_id, text, html=False, formatted_text=None, notice=False):
if html:
return self.send_message(room_id, {
- "body": unformatted_text or text,
+ "body": text,
"msgtype": "m.notice" if notice else "m.text",
"format": "org.matrix.custom.html",
- "formatted_body": text,
+ "formatted_body": formatted_text or text,
})
else:
return self.send_message(room_id, {
@@ -170,6 +172,14 @@ class IntentAPI:
def join_room(self, room_id):
return self._ensure_joined(room_id, ignore_cache=True)
+ def get_room_members(self, room_id):
+ return self.client.get_room_members(room_id)
+
+ def get_joined_users(self, room_id):
+ memberships = self.get_room_members(room_id)
+ return [membership["state_key"] for membership in memberships["chunk"] if
+ membership["content"]["membership"] == "join"]
+
def _ensure_joined(self, room_id, ignore_cache=False):
if ignore_cache and self.memberships.get(room_id, "") == "join":
return
diff --git a/mautrix_telegram/commands.py b/mautrix_telegram/commands.py
index 968258f6..d97ac954 100644
--- a/mautrix_telegram/commands.py
+++ b/mautrix_telegram/commands.py
@@ -15,6 +15,7 @@
# along with this program. If not, see .
from contextlib import contextmanager
import markdown
+from telethon.errors import *
command_handlers = {}
@@ -25,26 +26,34 @@ def command_handler(func):
class CommandHandler:
def __init__(self, context):
- self.appserv, self.db, log, self.config = context
+ self.az, self.db, log, self.config = context
self.log = log.getChild("commands")
- self.command_prefix = self.config["bridge.commands.prefix"]
+ self.command_prefix = self.config["bridge.command_prefix"]
self._room_id = None
+ self._is_management = False
+ self._is_portal = False
def handle(self, room, sender, command, args, is_management, is_portal):
- with self.handler(sender, room, command) as handle_command:
- handle_command(self, sender, args, is_management, is_portal)
+ with self.handler(sender, room, command, args, is_management, is_portal) as handle_command:
+ handle_command(self, sender, args)
@contextmanager
- def handler(self, sender, room, command):
+ def handler(self, sender, room, command, args, is_management, is_portal):
self._room_id = room
try:
command = command_handlers[command]
except KeyError:
+ print(sender.command_status)
if sender.command_status and "next" in sender.command_status:
+ args.insert(0, command)
command = sender.command_status["next"]
else:
command = command_handlers["unknown_command"]
+ self._is_management = is_management
+ self._is_portal = is_portal
yield command
+ self._is_management = None
+ self._is_portal = None
self._room_id = None
def reply(self, message, allow_html=False, render_markdown=True):
@@ -53,39 +62,152 @@ class CommandHandler:
"the `CommandHandler.run` context manager")
message = message.replace("$cmdprefix", self.command_prefix)
+ message = message.replace("$cmdprefix+sp ",
+ "" if self._is_management else f"{self.command_prefix} ")
html = None
if render_markdown:
html = markdown.markdown(message, safe_mode="escape" if allow_html else False)
elif allow_html:
html = message
- self.appserv.api.send_message_event(self._room_id, "m.room.message", {
- "msgtype": "m.notice",
- "body": message,
- "format": "org.matrix.custom.html" if html else None,
- "formatted_body": html or None,
- })
+ self.az.intent.send_text(self._room_id, message, formatted_text=html,
+ html=True if html else False, notice=True)
@command_handler
- def cancel(self, sender, args, is_management, is_portal):
- if sender.command_status:
+ def register(self, sender, args):
+ self.reply("Not yet implemented.")
+
+ @command_handler
+ def login(self, sender, args):
+ if not self._is_management:
+ return self.reply(
+ "`login` is a restricted command: you may only run it in management rooms.")
+ elif sender.logged_in:
+ return self.reply("You are already logged in.")
+ elif len(args) == 0:
+ return self.reply("**Usage:** `$cmdprefix+sp login `")
+ phone_number = args[0]
+ sender.client.send_code_request(phone_number)
+ sender.client.sign_in(phone_number)
+ sender.command_status = {
+ "next": command_handlers["enter_code"],
+ "action": "Login",
+ }
+ return self.reply(f"Login code sent to {phone_number}. Please send the code here.")
+
+ @command_handler
+ def enter_code(self, sender, args):
+ if not sender.command_status:
+ return self.reply("Request a login code first with `$cmdprefix+sp login `")
+ elif len(args) == 0:
+ return self.reply("**Usage:** `$cmdprefix+sp enter_code ")
+
+ try:
+ user = sender.client.sign_in(code=args[0])
sender.command_status = None
- return self.reply(f"{sender.command_status.action} cancelled.")
+ return self.reply(f"Successfully logged in as @{user.username}")
+ except PhoneNumberUnoccupiedError:
+ return self.reply("That phone number has not been registered."
+ "Please register with `$cmdprefix+sp register `.")
+ except PhoneCodeExpiredError:
+ return self.reply(
+ "Phone code expired. Try again with `$cmdprefix+sp login `.")
+ except PhoneCodeInvalidError:
+ return self.reply("Invalid phone code.")
+ except PhoneNumberAppSignupForbiddenError:
+ return self.reply(
+ "Your phone number does not allow 3rd party apps to sign in.")
+ except PhoneNumberFloodError:
+ return self.reply(
+ "Your phone number has been temporarily blocked for flooding. "
+ "The block is usually applied for around a day.")
+ except PhoneNumberBannedError:
+ return self.reply("Your phone number has been banned from Telegram.")
+ except SessionPasswordNeededError:
+ sender.command_status = {
+ "next": command_handlers["enter_password"],
+ "action": "Login (password entry)",
+ }
+ return self.reply("Your account has two-factor authentication."
+ "Please send your password here.")
+ except:
+ self.log.exception()
+ return self.reply("Unhandled exception while sending code."
+ "Check console for more details.")
+
+ @command_handler
+ def enter_password(self, sender, args):
+ if not sender.command_status:
+ return self.reply("Request a login code first with `$cmdprefix+sp login `")
+ elif len(args) == 0:
+ return self.reply("**Usage:** `$cmdprefix+sp enter_password ")
+
+ try:
+ user = sender.client.sign_in(password=args[0])
+ sender.command_status = None
+ return self.reply(f"Successfully logged in as @{user.username}")
+ except PasswordHashInvalidError:
+ return self.reply("Incorrect password.")
+ except:
+ self.log.exception()
+ return self.reply("Unhandled exception while sending password."
+ "Check console for more details.")
+
+ @command_handler
+ def logout(self, sender, args):
+ if not sender.logged_in:
+ return self.reply("You're not logged in.")
+ if sender.client.log_out():
+ return self.reply("Logged out successfully.")
+ return self.reply("Failed to log out.")
+
+ @command_handler
+ def ping(self, sender, args):
+ if not sender.logged_in:
+ return self.reply("You're not logged in.")
+ me = sender.client.get_me()
+ if me:
+ return self.reply(f"You're logged in as @{me.username}")
+ else:
+ return self.reply("You're not logged in.")
+
+ @command_handler
+ def search(self, sender, args):
+ self.reply("Not yet implemented.")
+
+ @command_handler
+ def pm(self, sender, args):
+ self.reply("Not yet implemented.")
+
+ @command_handler
+ def create(self, sender, args):
+ self.reply("Not yet implemented.")
+
+ @command_handler
+ def upgrade(self, sender, args):
+ self.reply("Not yet implemented.")
+
+ @command_handler
+ def cancel(self, sender, args):
+ if sender.command_status:
+ action = sender.command_status["action"]
+ sender.command_status = None
+ return self.reply(f"{action} cancelled.")
else:
return self.reply("No ongoing command.")
@command_handler
- def unknown_command(self, sender, args, is_management, is_portal):
- if is_management:
+ def unknown_command(self, sender, args):
+ if self._is_management:
return self.reply("Unknown command. Try `help` for help.")
else:
return self.reply("Unknown command. Try `$cmdprefix help` for help.")
@command_handler
- def help(self, sender, args, is_management, is_portal):
- if is_management:
+ def help(self, sender, args):
+ if self._is_management:
management_status = ("This is a management room: prefixing commands"
"with `$cmdprefix` is not required.\n")
- elif is_portal:
+ elif self._is_portal:
management_status = ("**This is a portal room**: you must always"
"prefix commands with `$cmdprefix`.\n"
"Management commands will not be sent to Telegram.")
@@ -100,15 +222,11 @@ _**Generic bridge commands**: commands for using the bridge that aren't related
_**Telegram actions**: commands for using the bridge to interact with Telegram._
**login** <_phone_> - Request an authentication code.
**logout** - Log out from Telegram.
+**ping** - Check if you're logged into Telegram.
**search** [_-r|--remote_] <_query_> - Search your contacts or the Telegram servers for users.
+**pm** <_id_> - Open a private chat with the given Telegram user ID.
**create** <_group/channel_> [_room ID_] - Create a Telegram chat of the given type for a Matrix room.
If the room ID is not specified, a chat for the current room is created.
**upgrade** - Upgrade a normal Telegram group to a supergroup.
-
-_**Temporary commands**: commands that will be replaced with more Matrix-y actions later._
-**pm** <_id_> - Open a private chat with the given Telegram user ID.
-
-_**Debug commands**: commands to help in debugging the bridge. Disabled by default._
-**api** <_method_> <_args_> - Call a Telegram API method. Args is always a single JSON object.
"""
return self.reply(management_status + help)
diff --git a/mautrix_telegram/matrix.py b/mautrix_telegram/matrix.py
index 5dec713d..a807a810 100644
--- a/mautrix_telegram/matrix.py
+++ b/mautrix_telegram/matrix.py
@@ -31,6 +31,8 @@ class MatrixHandler:
self.localpart_regex = re.compile(f"@{alias_format}:{hs}")
self.az.matrix_event_handler(self.handle_event)
+ self.az.intent.set_display_name(
+ self.config.get("appservice.bot_displayname", "Mautrix-Telegram Bridge"))
def is_puppet(self, mxid):
match = self.localpart_regex.match(mxid)
@@ -51,14 +53,9 @@ class MatrixHandler:
def handle_part(self, room, user):
self.log.debug(f"{user} left {room}")
- def is_management(self, room):
- memberships = self.az.intent.get_room_members(room)
- return [membership["state_key"] for membership in memberships["chunk"] if
- membership["content"]["membership"] == "join"]
-
def is_command(self, message):
text = message.get("body", "")
- prefix = self.config["bridge.commands.prefix"]
+ prefix = self.config["bridge.command_prefix"]
is_command = text.startswith(prefix)
if is_command:
text = text[len(prefix) + 1:]
@@ -78,7 +75,7 @@ class MatrixHandler:
if message["msgtype"] != "m.text":
return
- is_management = len(self.is_management(room)) == 2
+ is_management = len(self.az.intent.get_joined_users(room)) == 2
if is_command or is_management:
try:
command, arguments = text.split(" ", 1)
@@ -87,7 +84,8 @@ class MatrixHandler:
# Not enough values to unpack, i.e. no arguments
command = text
args = []
- self.commands.handle(room, sender, command, args, is_management, is_portal=portal is not None)
+ self.commands.handle(room, sender, command, args, is_management,
+ is_portal=portal is not None)
def filter_matrix_event(self, event):
return event["sender"] == self.az.bot_mxid or self.is_puppet(event["sender"])
diff --git a/mautrix_telegram/user.py b/mautrix_telegram/user.py
index 3bda746d..0b7ebd31 100644
--- a/mautrix_telegram/user.py
+++ b/mautrix_telegram/user.py
@@ -33,13 +33,16 @@ class User:
self.command_status = None
self.connected = False
- self.logged_in = False
self.client = None
self.by_mxid[mxid] = self
if tgid:
self.by_tgid[tgid] = self
+ @property
+ def logged_in(self):
+ return self.client.is_user_authorized()
+
def to_db(self):
return self.db.merge(DBUser(self.mxid, self.tgid))
@@ -57,7 +60,6 @@ class User:
config["telegram.api_hash"],
update_workers=2)
self.connected = self.client.connect()
- self.logged_in = self.client.is_user_authorized()
if self.logged_in:
self.sync_dialogs()
self.client.add_update_handler(self.update_catch)