about summary refs log tree commit diff
path: root/tooter.py
blob: f34209b7135f5051ee8f23404ef3e51f5ec76d28 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#!/usr/bin/env python3

from mastodon import Mastodon
from irctokens import build, Line
from ircrobots import Bot as BaseBot
from ircrobots import Server as BaseServer
from ircrobots import ConnectionParams, SASLUserPass
import asyncio
import emoji
import glob
import json
import os
import re
import sys

HELPTEXT = "helo i can send toots from irc: @tildeverse@tilde.zone - from @tildeteam from the #team channel)"


def masto_from_json(conf):
    conf = json.load(conf)
    return Mastodon(
        client_id=conf["client_id"],
        client_secret=conf["client_secret"],
        access_token=conf["access_token"],
        api_base_url=conf["base_url"],
    )


masto = {}
# load masto creds
for cred in glob.glob("tilde*.json"):
    shortname, _ = os.path.splitext(cred)
    with open(cred, "r") as f:
        masto[shortname] = masto_from_json(f)

# do setup
path = os.path.dirname(os.path.abspath(__file__))

with open(os.path.join(path, "config.json"), "r") as f:
    config = json.load(f)

if os.path.isfile(os.path.join(path, "account.json")):
    with open(os.path.join(path, "account.json"), "r") as f:
        account = json.load(f)

channels = config["channels"]
if len(sys.argv) > 1:
    for c in sys.argv[1:]:
        channels.append("#" + c)


def think(line):
    chan = line.params[0]
    words = line.params[1].split(" ")

    if len(words) > 0:
        cmd = words[0].lower()
        if cmd == "!toot":
            if len(words) >= 2:
                status = emoji.emojize(" ".join(words[1:]), use_aliases=True)
                if chan == "#team":
                    res = masto["tildeteam"].toot(status)
                elif chan == "#club":
                    res = masto["tildeclub"].toot(status)
                else:
                    res = masto["tildeverse"].toot(status)
                print(res)
                return "tooted! {}".format(res["url"])
            else:
                return HELPTEXT
        elif cmd == "!source":
            return "https://tildegit.org/ben/tooter"
        elif cmd in ["!botlist", "!toothelp"]:
            return HELPTEXT


class Server(BaseServer):
    async def line_send(self, line: Line):
        print(f"{self.name} > {line.format()}")

    async def line_read(self, line: Line):
        print(f"{self.name} < {line.format()}")
        if line.command == "001":
            print(f"connected to {self.isupport.network}")
            await self.send(build("JOIN", [",".join(channels)]))
            await self.send(build("MODE", [self.nickname, "+B"]))

        if line.command == "INVITE":
            print(f"received invite to {line.params[1:]}")
            await self.send(build("JOIN", line.params[1:]))

        if (
            line.command == "PRIVMSG"
            and self.has_channel(line.params[0])
            and self.has_user(line.hostmask.nickname)
            and not line.hostmask is None
            and not self.casefold(line.hostmask.nickname) == self.nickname_lower
            and not ("batch" in line.tags and line.tags["batch"] == "1")
        ):
            response = think(line)
            if response is not None:
                await self.send(build("PRIVMSG", [line.params[0], response]))


class Bot(BaseBot):
    def create_server(self, name: str):
        return Server(self, name)


async def main():
    bot = Bot()

    params = ConnectionParams(
        config["botnick"],
        host=config["address"],
        port=config["port"],
        tls=config["tls"],
        sasl=SASLUserPass(account["username"], account["password"]),
    )

    await bot.add_server("tilde", params)
    await bot.run()


if __name__ == "__main__":
    asyncio.run(main())