matrix搭建以及机器人配置

geteshi
2023-11-13 / 0 评论 / 201 阅读 / 正在检测是否收录...

matrix的安装

1. 创建配置文件

sudo docker run -it --rm -v /tmp/data:/data -e SYNAPSE_SERVER_NAME=你的域名 -e SYNAPSE_REPORT_STATS=yes matrixdotorg/synapse:latest generate

其中/tmp/data可以换,记得就行,这里用这个展示

2. 到/tmp/data里面找到homeserver.yaml编辑


# Configuration file for Synapse.
#
# This is a YAML file: see [1] for a quick introduction. Note in particular
# that *indentation is important*: all the elements of a list or dictionary
# should have the same indentation.
#
# [1] https://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html
#
# For more information on how to configure Synapse, including a complete accounting of
# each option, go to docs/usage/configuration/config_documentation.md or
# https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html
server_name: "matrix域名"
pid_file: /data/homeserver.pid
listeners:
  - port: 8008   # 容器的端口号,不改
    tls: false
    type: http
    x_forwarded: true
    resources:
      - names: [client, federation]
        compress: false
# database:
#   name: sqlite3
#   args:
#     database: /data/homeserver.db
database:  # 数据库设置,如果人少的话推荐上面的sqlite,pgdb太伤人了
  name: psycopg2
  args:
    user: matrix
    password: 24W53MDwk8TyBh7z
    database: matrix
    host: # 你懂的
    cp_min: 5
    cp_max: 10
#   allow_unsafe_locale: true
log_config: "/data/matrix域名.log.config"  # 自动生成的,一般不用改
media_store_path: /data/media_store
registration_shared_secret: "c:*RWamLStS9J,sQhm7=dwGpC2#DVKRtwCkCBvPwMJ&p"
report_stats: true
macaroon_secret_key: "g3@hjR7pMO2&enhNM*jKZq*l3=JS@d~Jl8J3ZvJ~smCkLD"
form_secret: "I,kV-blS-oVG3h_c2kiQ&kH0P+=@V&pMedyu4~E-i;BzP"
signing_key_path: "/data/matrix域名.signing.key"  # 自动生成的,一般不用改
trusted_key_servers:
  - server_name: "matrix域名"
  
# 开放注册
enable_registration: true
# 注册不需要验证,没有配置邮箱的时候推荐这个不验证
enable_registration_without_verification: false
# 注册需要验证邮箱
registrations_require_3pid:
  - email

# 邮箱配置,这里用88邮箱演示
email:
  smtp_host: "smtp.88.com"
  smtp_port: 465
  smtp_user: "发送的邮箱地址"
  smtp_pass: "密码,你懂的"
  force_tls: true
  require_transport_security: true
  enable_tls: true
  notif_from: "通知的邮箱地址"
  app_name: "聊天室"
  enable_notifs: true
  notif_for_new_users: true
  client_base_url: "https://element的域名"
  validation_token_lifetime: 15m
  invite_client_location: https://element的域名

3. docker-compose 文件

version: "3.3"

services:
  synapse:
    image: "matrixdotorg/synapse:latest"
    container_name: "matrix_synapse"
    restart: unless-stopped
    ports:
      - 8008:8008
    volumes:
      - "./data:/data" # 这个data需要上面的/tmp/data,我的这个文件放在/tmp里面,所以用了./data
    environment:
      VIRTUAL_HOST: "matrix域名"
      VIRTUAL_PORT: 8008
      LETSENCRYPT_HOST: "matrix域名"
      SYNAPSE_SERVER_NAME: "matrix域名"
      SYNAPSE_REPORT_STATS: "yes"
      

  element-web:
    ports:
      - '80:80'
    volumes:
        - './data/config.json:/app/config.json'
    image: vectorim/element-web
    restart: unless-stopped

搭建到这里就完了

使用nio-bot

安装这两个库

pip nio-bot
pip install nio-bot[e2ee,cli]

实例文件

import logging

# from niobot import NioBot, Context
import niobot
from apscheduler.schedulers.asyncio import AsyncIOScheduler


logging.basicConfig(level=logging.INFO)
bot = niobot.NioBot(
    homeserver="https://test.test.test",  # your homeserver
    user_id="@test:test.test.test",  # the user ID to log in as (Fully qualified)
    device_id="nio-message",
    store_path=r"./store/",
    command_prefix="!",  # the prefix to respond to (case sensitive, must be lowercase if below is True)
    case_insensitive=True,  # messages will be lower()cased before being handled. This is recommended.
    owner_id="@user:test.test.test",  # The user ID who owns this bot. Optional, but required for bot.is_owner(...).
    ignore_self=True
)
# bot.mount_module("test.py")


def schedule_auto_messages():
    scheduler = AsyncIOScheduler()
    # 测试的定时任务
    # scheduler.add_job(test, "cron", second="*/3", id="test", misfire_grace_time=180, args=[bot])
    scheduler.start()

@bot.on_event("ready")
async def on_ready(sync_result: niobot.SyncResponse):
    print("Logged in!")
    schedule_auto_messages()


@bot.command("ping")
async def ping_command(ctx: niobot.Context):
    latency = ctx.latency
    # await ctx.reply("Pong!")
    await ctx.respond(f"Pong! `{latency:.2f}ms` latency.")


# A command with arguments
@bot.command(name="echo")
async def echo_command(ctx: niobot.Context, message: str):
    print("这里的输出")
    await ctx.respond(message)


# bot.run(password="password")  # starts the bot with a password. If you already have a login token, see:
bot.run(access_token="token")  # starts the bot with a login token.

获取token

使用这个命令

niocli get-access-token -U '@test:test.test.test' -D '设备id->device_id'

验证设备

https://github.com/poljar/matrix-nio/blob/main/examples/verify_with_emoji.py
通过表情符号验证,申请token使用上面那个,获取token的方式,之后用这个验证,需要创建一个文件

// credentials.json
{"homeserver": "https://matrix.example.org", "user_id": "@test:matrix.example.org", "device_id": "niobot2", "access_token": "上面那个"}

之后直接运行,多尝试几次,不成功就把store里面的文件删掉。重新获取token,先运行机器人的文件,再运行这个表情包验证文件!!

0

评论 (0)

取消