Examples

A Basic Echo Bot

"""
Example Usage:

random_user
      !echo something

echo_bot
      something
"""

import simplematrixbotlib as botlib

creds = botlib.Creds("https://home.server", "user", "pass")
bot = botlib.Bot(creds)
PREFIX = '!'


@bot.listener.on_message_event
async def echo(room, message):
    match = botlib.MessageMatch(room, message, bot, PREFIX)

    if match.is_not_from_this_bot() and match.prefix() and match.command(
            "echo"):

        await bot.api.send_text_message(room.room_id,
                                        " ".join(arg for arg in match.args()))


bot.run()

A “High-Five” Bot

"""
Example Usage:

random_user
      !count

echo_bot
      The bot has been high-fived 10 times!

random_user
      !high_five

echo_bot
      random_user high-fived the bot!"

random_user
      !count

echo_bot
      The bot has been high-fived 11 times!
"""

import simplematrixbotlib as botlib

creds = botlib.Creds("https://example.org", "hight_five_bot", "secretpassword")
bot = botlib.Bot(creds)

PREFIX = '!'

try:
    with open("high_fives.txt", "r") as f:
        bot.total_high_fives = int(f.read())
except FileNotFoundError:
    bot.total_high_fives = 0


@bot.listener.on_message_event
async def bot_help(room, message):
    bot_help_message = f"""
    Help Message:
        prefix: {PREFIX}
        commands:
            help:
                command: help, ?, h
                description: display help command
            give high fives:
                command: high_five, hf
                description: high-five the bot!
            count:
                command: count, how_many, c
                description: show amount of high fives
                """
    match = botlib.MessageMatch(room, message, bot, PREFIX)
    if match.is_not_from_this_bot() and match.prefix() and (
            match.command("help") or match.command("?") or match.command("h")):
        await bot.api.send_text_message(room.room_id, bot_help_message)


@bot.listener.on_message_event
async def high_five(room, message):
    match = botlib.MessageMatch(room, message, bot, PREFIX)
    if match.is_not_from_this_bot() and match.prefix() and (
            match.command("high_five") or match.command("hf")):

        bot.total_high_fives += 1
        with open("high_fives.txt", "w") as f:
            f.write(str(bot.total_high_fives))

        await bot.api.send_text_message(
            room.room_id, f"{message.sender} high-fived the bot!")


@bot.listener.on_message_event
async def high_five_count(room, message):
    match = botlib.MessageMatch(room, message, bot, PREFIX)
    if match.is_not_from_this_bot() and match.prefix() and (
            match.command("count") or match.command("how_many")
            or match.command("c")):
        await bot.api.send_text_message(
            room.room_id,
            f"The bot has been high-fived {str(bot.total_high_fives)} times!")


bot.run()

A Rock Paper Scissors Bot

import simplematrixbotlib as botlib
import os
import random

creds = botlib.Creds("https://example.org", "echo_bot", "secretpassword")
bot = botlib.Bot(creds)

PREFIX = '!'


@bot.listener.on_message_event
async def help_message(room, message):
    match = botlib.MessageMatch(room, message, bot, PREFIX)
    if not (match.is_not_from_this_bot() and match.prefix()
            and match.command("help")):
        return

    message = (f"""
    Help
    ============================
    What is this bot?
        Rock Paper Scissors Bot is a Matrix bot that plays rock paper scissors with room members and is written in Python using the simplematrixbotlib package.
    Commands?
        {PREFIX}help - show this message
        {PREFIX}play <rock/paper/scissors> - play the game by making a choice
    """)

    await bot.api.send_text_message(room.room_id, message)


@bot.listener.on_message_event
async def make_choice(room, message):
    match = botlib.MessageMatch(room, message, bot, PREFIX)
    if not (match.is_not_from_this_bot() and match.prefix()
            and match.command("play")):
        return

    temp = True
    if not match.args():
        temp = False
    elif "rock" == match.args()[0]:
        choice = "rock"
    elif "paper" == match.args()[0]:
        choice = "paper"
    elif "scissors" == match.args()[0]:
        choice = "scissors"
    else:
        temp = False

    victory_table = {"rock": "scissors", "scissors": "paper", "paper": "rock"}

    if temp:
        bot_choice = random.choice(["rock", "paper", "scissors"])

        await bot.api.send_text_message(room.room_id, f"You choose {choice}.")
        await bot.api.send_text_message(room.room_id,
                                        f"The bot chose {bot_choice}.")

        if choice == bot_choice:
            await bot.api.send_text_message(room.room_id, "You Tied!")
        if bot_choice == victory_table[choice]:
            await bot.api.send_text_message(room.room_id, "You Won!")
        if choice == victory_table[bot_choice]:
            await bot.api.send_text_message(room.room_id, "You Lost!")

    else:
        await bot.api.send_text_message(
            room.room_id,
            "Invalid choice. Please choose \"rock\", \"paper\", or \"scissors\"."
        )


bot.run()

A Reaction Echo Bot

"""
Example Usage:

random_user
      !echo something

random_user2
      *reacts with 👍️

echo_reaction_bot
      Reaction: 👍️
"""

import simplematrixbotlib as botlib

creds = botlib.Creds("https://example.com", "echo_reaction_bot", "password")
bot = botlib.Bot(creds)


@bot.listener.on_reaction_event
async def echo_reaction(room, event, reaction):
    resp_message = f"Reaction: {reaction}"
    await bot.api.send_text_message(room.room_id, resp_message)


bot.run()

Echo Bot within a Docker Container

FROM python:latest

RUN python -m pip install simplematrixbotlib

ADD echo.py echo.py

CMD [ "python", "echo.py" ]

Echo Bot using Config Files

"""
Example Usage:

random_user
      !echo something

echo_bot
      something
"""

import simplematrixbotlib as botlib

creds = botlib.Creds("https://home.server", "user", "pass")

config = botlib.Config()
config.load_toml("config.toml")

bot = botlib.Bot(creds, config)
PREFIX = '!'


@bot.listener.on_message_event
async def echo(room, message):
    match = botlib.MessageMatch(room, message, bot, PREFIX)

    if match.is_not_from_this_bot() and match.prefix() and match.command(
            "echo"):

        await bot.api.send_text_message(room.room_id,
                                        " ".join(arg for arg in match.args()))


bot.run()

Bot Config File in TOML format

[simplematrixbotlib.config]
join_on_invite = false

Echo Bot with Allow/Blocklist Config File

#Used with Bot Config File in TOML format
"""
Example Usage:

admin1
      !echo something

echo_bot
      something

admin3
      !echo something

user1
      !echo something
"""

import simplematrixbotlib as botlib

creds = botlib.Creds("https://home.server", "user", "pass")

config = botlib.Config()
config.load_toml("config.toml")

bot = botlib.Bot(creds, config)
PREFIX = '!'


@bot.listener.on_message_event
async def echo(room, message):
    match = botlib.MessageMatch(room, message, bot, PREFIX)

    if match.is_not_from_this_bot() \
       and match.is_from_allowed_user() \
       and match.prefix() \
       and match.command("echo"):

        await bot.api.send_text_message(room.room_id,
                                        " ".join(arg for arg in match.args()))


bot.run()

Bot Config File in TOML format

[simplematrixbotlib.config]
allowlist = ['@admin.*:example\.org']
blocklist = ['@admin3:example\.org']

Using Allow/Blocklist Interactively + Config File

"""
Example Usage:
note the escaped dot (\.)

user1
      !allow @user2:example\.org

admin1
      !allow @user1:example\.org, @admin2:example\.org

echo_bot
      allowing @user1:example\.org, @admin2:example\.org

user1
      !allow @user2:example\.org

echo_bot
      allowing @user2:example\.org

admin2
      !disallow @user1:example\.org
"""

import simplematrixbotlib as botlib

creds = botlib.Creds("https://home.server", "user", "pass")

config = botlib.Config()
config.load_toml("config_allow_interactive.toml")

bot = botlib.Bot(creds, config)
PREFIX = '!'


@bot.listener.on_message_event
async def echo(room, message):
    match = botlib.MessageMatch(room, message, bot, PREFIX)

    if match.is_not_from_this_bot() \
       and match.is_from_allowed_user() \
       and match.prefix():

        if match.command("allow"):
            bot.config.add_allowlist(set(match.args()))
            await bot.api.send_text_message(
                room.room_id,
                f'allowing {", ".join(arg for arg in match.args())}')

        if match.command("disallow"):
            bot.config.remove_allowlist(set(match.args()))
            await bot.api.send_text_message(
                room.room_id,
                f'disallowing {", ".join(arg for arg in match.args())}')


bot.run()

Bot Config File in TOML format

[simplematrixbotlib.config]
allowlist = ['@admin1:example\.org']