Coder Social home page Coder Social logo

matrix-bot-base's Introduction

Matrix Bot Base

This repository contains an abstraction layer to build bots using Trixnity.

I'm typically online in the Trixnity channel. So feel free to tag me there if you have any questions.

Usage

To use this library, you need to add it as a dependency to your project. You can do this by adding the following to your pom.xml:

<dependency>
    <groupId>org.fuchss</groupId>
    <artifactId>matrix-bot-base</artifactId>
    <version>VERSION</version>
</dependency>

This library contains helper classes to build bots. Start by defining the creation of bot by creating a Main.kt file:

private lateinit var commands: List<Command>

fun main() {
    runBlocking {
        val config: IConfig = // Load config here 
            commands = listOf(HelpCommand(config, "FancyBot") { commands }, QuitCommand(config), LogoutCommand(config), ChangeUsernameCommand(), /* Custom commands here */)

        val matrixClient = getMatrixClient(config)

        val matrixBot = MatrixBot(matrixClient, config)
        matrixBot.subscribeContent { event -> handleTextMessage(commands, event.roomIdOrNull, event.senderOrNull, event.content, matrixBot, config) }
        matrixBot.subscribeContent { event -> handleEncryptedTextMessage(commands, event, matrixClient, matrixBot, config) }

        val loggedOut = matrixBot.startBlocking()

        // These lines will be reached if the bot shuts down
        if (loggedOut) {
            // Cleanup database stuff as you like (e.g., delete database files)
            val databaseFiles = listOf(File(config.dataDirectory + "/database.mv.db"), File(config.dataDirectory + "/database.trace.db"))
            databaseFiles.filter { it.exists() }.forEach { it.delete() }
        }
    }
}

private suspend fun getMatrixClient(config: Config): MatrixClient {
    val existingMatrixClient = MatrixClient.fromStore(createRepositoriesModule(config), createMediaStore(config)).getOrThrow()
    if (existingMatrixClient != null) {
        return existingMatrixClient
    }

    val matrixClient = MatrixClient.login(
        baseUrl = Url(config.baseUrl),
        identifier = IdentifierType.User(config.username),
        password = config.password,
        repositoriesModule = createRepositoriesModule(config),
        mediaStore = createMediaStore(config),
        initialDeviceDisplayName = "An interesting bot",
    ).getOrThrow()

    return matrixClient
}

You also need a suitable configuration for your bot. You may use a class like this:

/**
 * This is the configuration template of the mensa bot.
 * @param[prefix] the command prefix the bot listens to. By default, "bot"
 * @param[baseUrl] the base url of the matrix server the bot shall use
 * @param[username] the username of the bot's account
 * @param[password] the password of the bot's account
 * @param[dataDirectory] the path to the databases and media folder
 * @param[admins] the matrix ids of the admins. E.g. "@user:invalid.domain"
 * @param[users] the matrix ids of the authorized users or servers. E.g. "@user:invalid.domain" or ":invalid.domain"
 */
data class Config(
    @JsonProperty override val prefix: String = "bot",
    @JsonProperty override val baseUrl: String,
    @JsonProperty override val username: String,
    @JsonProperty override val password: String,
    @JsonProperty override val dataDirectory: String,
    @JsonProperty override val admins: List<String>,
    @JsonProperty override val users: List<String>,
) : IConfig {
    companion object {
        private val log: Logger = LoggerFactory.getLogger(Config::class.java)

        /**
         * Load the config from the file path. You can set "CONFIG_PATH" in the environment to override the default location ("./config.json").
         */
        fun load(): Config {
            val configPath = System.getenv("CONFIG_PATH") ?: "./config.json"
            val configFile = File(configPath)
            if (!configFile.exists()) {
                error("Config ${configFile.absolutePath} does not exist!")
            }

            val config: Config = ObjectMapper().registerKotlinModule().readValue(configFile)
            log.info("Loaded config ${configFile.absolutePath}")
            config.validate()
            return config
        }
    }
}

This creates a bot that can be used to handle text messages. The bot will automatically handle the following commands:

  • help - Shows a list of all available commands
  • quit - Quits the bot
  • logout - Quits the bot and logs out all sessions
  • name {username} - Changes the username of the bot

matrix-bot-base's People

Contributors

actions-user avatar dependabot[bot] avatar dfuchss avatar

Stargazers

 avatar Benedict avatar

Watchers

 avatar

matrix-bot-base's Issues

Add tests

Find some time to create basic tests

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.