This howto describes how to setup the Matrix (element.io) provider included in discourse-chat-integration.
Thanks to @ara4n and members of the #matrix-dev:matrix.org room for their help with this integration
Install
The discourse-chat-integration plugin is bundled with Discourse. Ensure it is enabled by setting chat_integration_enabled to true in your site settings. For more details, see the discourse-chat-integration plugin topic.
Set up Matrix
These instructions assume you are using the element.io web client. Equivalent steps should be possible using other interfaces.
Create a user account for your bot. You’ll probably want to write down the password somewhere in case you want to log back in later. Discourse does not need it.
Use the interface to join any rooms that you want to be able to send notifications to
Open the user settings by clicking your avatar in the top left, then All Settings
Configure the bot’s display name and avatar
Switch to the “Help and About” tab, scroll down to “Advanced”, and copy the Homeserver address and your “Access Token” - you’ll need them later.
DO NOT CLICK LOG OUT. If you do, the Access Token will be invalidated, and it won’t work. Instead, just close the incognito window. If you forgot to open an incognito window, go back to step 1
Set up Discourse
In your Discourse site settings, enter your home server address in the chat_integration_matrix_homeserver setting. Make sure to include the protocol. (e.g. https://matrix.org). Do not include a trailing slash.
Paste the access token you copied earlier into the chat_integration_matrix_access_token site setting
Enable chat_integration_matrix_enabled
Go to the Plugins tab, then Chat Integrations
Go to the Matrix tab, then Create Channel
Enter a name for the channel (this is only displayed in the admin interface, it can be anything)
Enter the “Room ID” for a room that you want to send notifications to. In the Element web client, you can find it by opening your room, clicking the name at the top, then scroll to the bottom. It will look something like
!cdGUowUAqlgLHVerqE:matrix.org
Note: Newer Matrix Room v12 IDs may not include the :server suffix (e.g. !abcdefghijkl). Both formats are supported.
Save Channel
Use the Test button on the channel you just created to check that everything’s working. You should see something like this:
At the time of writing, there does not seem to be a way of obtaining an “access token” for a “bot” in a user-friendly way. The incognito window solution is the most user-friendly way I could find
This plugin sends rich text messages using the org.matrix.custom.html format, which is part of the Matrix spec. Clients that do not support formatted messages will fall back to a plain text message.
By default, messages are sent as m.notice (which Matrix clients typically render more quietly). You can change this to m.text by disabling the chat_integration_matrix_use_notice site setting.
There is no provision in this implementation for ‘refreshing’ access tokens. This is based on the understanding that the majority of homeservers currently in use do not expire tokens. If this changes in the future, this will need to be revisited.
I just tried setting up a matrix integration using the instructions above, and it all worked ok. Can you confirm that you’re running the latest version of Discourse and this plugin?
Are you using the matrix.org homeserver, or your own homeserver? The 422 error is coming from that server.
I would suggest double checking your channel identifier, and also your matrix access token in your Discourse site settings.
У меня абсолютно та же проблема, что и у @almereyda. @david, не могли бы вы обновить инструкцию по получению «Access Token», пожалуйста? (Riot, кажется, активно развивается )
+“Журнал диагностики”
Я только что сам проверил настройку, и всё, кажется, работает нормально. Есть несколько предположений:
Зашифрованы ли ваши комнаты? Не уверен, нужно ли нам дополнительно дорабатывать поддержку зашифрованных комнат.
Возможно, токены доступа истекают через некоторое время. Раньше, когда я создавал интеграцию в 2017 году, такого не было, но это было очень давно . На этой неделе я ещё раз проверю свою локальную конфигурацию и посмотрю, всё ли ещё работает.
Для протокола: @mattdm и я смогли выяснить, что проблема вызвана лишним слэшем в конце URL-адреса домашнего сервера в настройках Discourse.
Я добавил примечание об этом в инструкцию в первом посте и также обновил инструкции по токенам доступа, чтобы они соответствовали новейшему интерфейсу element.io.
При установке последней версии плагина чата (коммит ba40ede510986f74a23345082ac578e126467b97) и настройке тестовой комнаты Matrix (незашифрованной, публичной) при попытке теста как описано выше возникает ошибка HTTP 500. Тот же симптом — бесконечный спиннер, требующий обновления страницы.
Токен доступа учётной записи бота был независимо проверен путём отправки сообщения в комнату через API (_matrix/client/r0/rooms/{room_id}/send/m.room.message) на наш собственный сервер Matrix.
В логах Discourse показано:
Started POST "/admin/plugins/chat-integration/test" for 141.142.60.55 at 2022-11-16 18:16:47 +0000
Processing by DiscourseChatIntegration::ChatController#test as */*
Parameters: {"channel_id"=>"107", "topic_id"=>"466"}
Completed 500 Internal Server Error in 62ms (ActiveRecord: 0.0ms | Allocations: 10109)
NameError (uninitialized constant FinalDestination::HTTP)
app/controllers/application_controller.rb:387:in `block in with_resolved_locale'
app/controllers/application_controller.rb:387:in `with_resolved_locale'
lib/middleware/omniauth_bypass_middleware.rb:71:in `call'
lib/content_security_policy/middleware.rb:12:in `call'
lib/middleware/anonymous_cache.rb:361:in `call'
config/initializers/100-quiet_logger.rb:23:in `call'
config/initializers/100-silence_logger.rb:31:in `call'
lib/middleware/enforce_hostname.rb:23:in `call'
lib/middleware/request_tracker.rb:198:in `call'
Я не пробовал, но это было бы интересно. Вы имеете в виду объединение всех постов в один тред для уменьшения загромождения каналов или речь идет о публикации ответов на темы в треде Matrix?