Мост Matrix-Telegram
Обновлено 23 сентября 2019
Регистрация API
Для работы моста Matrix-Telegram зарегистрируйте API:

Для запуска моста понадобится api_id api_hash, а также адреса MTProto серверов
Регистрация бота
В клиенте Telegram перейдите на диалог BotFather, кликнув по ссылке.
Начните диалог и создайте бота example_bot следующими сообщениями:
/start /newbot example_bot
Вы получите сообщение вида:
Done! Congratulations on your new bot. You will find it at t.me/example_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.
Use this token to access the HTTP API:
123456789:abcdefghijklmniopqrstuvwxyzABCDEFGH
Keep your token secure and store it safely, it can be used by anyone to control your bot.
For a description of the Bot API, see this page: https://core.telegram.org/bots/api
Запомните полученый BOT_TOKEN 123456789:abcdefghijklmniopqrstuvwxyzABCDEFGH.
Дайте доступ боту к сообщениями в группах, которых он будет находится, следующими сообщениями:
/setprivacy @example_bot Disable
Активируйте бота, перейдя по ссылке t.me/example_bot и отправив ему сообщение:
/start
Подготовка LXC контейнера
Мы рекомендуем выполнить настройку моста в отдельном контейнере, настроив его согласно инструкции.
Установка программного обеспечения
Установите пакет FFmpeg, используемый сервисом для работы с видеоконтентом Telegram:
emerge -a media-video/ffmpeg
Создайте и активируйте виртуальное окружение для Python:
mkdir -p /var/calculate/matrix-telegram
cd /var/calculate/matrix-telegram
python3 -m venv .
source bin/activate
Установите в виртуальное окружение сервиса Matrix-Telegram и модуль для работы через SOCKS5:
pip install --upgrade mautrix-telegram[all]
pip install PySocks
Скопируйте файл настроек example-config.yaml в config.yaml:
cp example-config.yaml config.yaml
Выполните настройку моста, где:
https://matrix.example.org- адрес до вашего сервера Matrixmatrix.example.org- домен MXIDhttp://matrix-telegram:8080- адрес сервиса моста123456- api_id сформированный ранееsecret_hash- api_hash сформированный ранее
homeserver:
# The address that this appservice can use to connect to the homeserver.
address: https://matrix.example.org
# The domain of the homeserver (for MXIDs, etc).
domain: matrix.example.org
appservice:
address: http://matrix-telegram:8080
# Public part of web server for out-of-Matrix interaction with the bridge.
# Used for things like login if the user wants to make sure the 2FA password isn't stored in
# the HS database.
public:
# Whether or not the public-facing endpoints should be enabled.
enabled: false
# Permissions for using the bridge.
# Permitted values:
# relaybot - Only use the bridge via the relaybot, no access to commands.
# user - Relaybot level + access to commands to create bridges.
# puppeting - User level + logging in with a Telegram account.
# full - Full access to use the bridge, i.e. previous levels + Matrix login.
# admin - Full access to use the bridge and some extra administration commands.
# Permitted keys:
# * - All Matrix users
# domain - All users on that homeserver
# mxid - Specific user
permissions:
"*": "relaybot"
"@admin:matrix.example.org": "admin"
telegram:
api_id: 123456
api_hash: secret_hash
bot_token: bot_token
Для использования SOCKS5 1.2.3.4:1080 добавьте следующие настройки:
telegram:
# Telethon proxy configuration.
# You must install PySocks from pip for proxies to work.
proxy:
# Allowed types: disabled, socks4, socks5, http
type: socks5
# Proxy IP address and port.
address: 1.2.3.4
port: 1080
# Whether or not to perform DNS resolving remotely.
rdns: true
# Proxy authentication (optional).
username: "sockuser"
password: "secret"
Сгенерируйте регистрационный файл, который позволит приложению взаимодействовать с Matrix-сервером:
python -m mautrix_telegram -g -r registration_telegram.yaml
Скопируйте регистрационный файл на сервер Synapse:
scp registration_telegram.yaml root@synapse:/var/calculate/synapse/
Добавьте файл регистрации в настройку Synapse:
app_service_config_files:
- registration_telegram.yaml
Перезапустите Synapse:
/etc/init.d/synapse restart
Выполните настройку базу данных для моста
alembic upgrade head
Запуск моста
Создайте сценарий OpenRC для управления демоном Matrix Telegram bridge:
#!/sbin/openrc-run # Copyright 2019 Gentoo Authors # Distributed under the terms of the GNU General Public License v2 name="Matrix-Telegram daemon" description="Matrix Telegram bridge daemon" command=/var/calculate/matrix-telegram/bin/python3 command_args="-m mautrix_telegram -r registration_telegram.yaml" directory=/var/calculate/matrix-telegram pidfile="/run/matrixtelegram.pid" command_background=true
Установите права на запуск:
chmod 755 /etc/init.d/matrix-telegram-bridge
Запустите демон:
/etc/init.d/matrix-telegram-bridge start
Добавьте демон в автозагрузку:
rc-update add matrix-telegram-bridge
Объединение комнат Matrix с группами Telegram
Получение идентификатора группы Telegram
Пригласите бота Telegram в нужную группу
curl "https://api.telegram.org/botBOT_TOKEN/getUpdates
{"ok":true,"result":[{"update_id":123451234,
"message":{"message_id":12345,"from":{"id":123451234,"is_bot":false,"first_name":"User","username":"Username"},
"chat":{"id":-100123456789,
"title":"Groupname","username":"calculate_talk","type":"supergroup"},
"date":1553239850,"new_chat_participant":
{"id":123451234,"is_bot":true,"first_name":"Example bot","username":"example_bot"},"new_chat_member":{"id":123451234,"is_bot":true,"first_name":"Example bot","username":"example_bot"},"new_chat_members":[{"id":123456789,"is_bot":true,"first_name":"Example bot","username":"example_bot"}]}}]}
Получение идентификатора канала Telegram
Назначте бота администратором канала и отправьте сообщение /id
curl "https://api.telegram.org/botBOT_TOKEN/getUpdates
"channel_post":{"message_id":123,
"chat":{"id":-1001123456789,
"title":"Example Channel","type":"channel"},"date":1553242405,"text":"/id","entities":[{"offset":0,"length":3,"type":"bot_command"}]}}]}
Объединение комнаты Matrix c каналом Telegram
Пригласите бота @telegrambot:matrix.example.org в комнату.
Выполните объединение текущей комнаты с каналом или группой телеграм по их идентификатору -1001123456789, отправив в общий чат сообщение:
!tg bridge -1001123456789 !tg continue