summary refs log tree commit diff
path: root/src/main.go
blob: 1837cc1889e1c2f9ac3e255541221f6186908d71 (plain)
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
// Copyright (C) 2017 Tulir Asokan
// Copyright (C) 2018-2020 Luca Weiss
// Copyright (C) 2023 Tulir Asokan
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

// This is the sourcecode for the "remarvin" bot, a quick and dirty marvin bot

// TODO(emile): figure out how to get the whole crypto foo runnning, as it isn't working using the
//              example code provided in the mautrix/go repo

package main

import (
	"context"
	"errors"
	"flag"
	"fmt"
	"os"
	"strings"
	"sync"
	"time"

	"github.com/chzyer/readline"
	//  _ "github.com/mattn/go-sqlite3"
	"github.com/rs/zerolog"
	"go.mau.fi/util/exzerolog"

	"maunium.net/go/mautrix"
	//  "maunium.net/go/mautrix/crypto/cryptohelper"
	"maunium.net/go/mautrix/event"
	"maunium.net/go/mautrix/id"
)

var homeserver = flag.String("homeserver", "", "Matrix homeserver")
var username = flag.String("username", "", "Matrix username localpart")
var accesstokenpath = flag.String("accesstokenpath", "", "Matrix accesstoken path")

// var password = flag.String("password", "", "Matrix password")
// var database = flag.String("database", "mautrix-example.db", "SQLite database path")

var debug = flag.Bool("debug", false, "Enable debug logs")

func main() {
	flag.Parse()

	// read the accesstoken
	dat, err := os.ReadFile(*accesstokenpath)
	if err != nil {
		_, _ = fmt.Fprintf(os.Stderr, "Couldn't read the accesstokenpath: %s\n", *accesstokenpath)
		os.Exit(1)
	}
	accesstoken := strings.TrimSuffix(string(dat), "\n")

	if *username == "" || *homeserver == "" || accesstoken == "" {
		_, _ = fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
		flag.PrintDefaults()
		os.Exit(1)
	}

	// create a new client using the given username, homeserver and accesstoken
	userID := id.NewUserID(*username, *homeserver)
	client, err := mautrix.NewClient(*homeserver, userID, accesstoken)
	if err != nil {
		panic(err)
	}

	// there's a prompt for manual intervention
	rl, err := readline.New("[no room]> ")
	if err != nil {
		panic(err)
	}
	defer rl.Close()

	// some fancy logging from the example
	log := zerolog.New(zerolog.NewConsoleWriter(func(w *zerolog.ConsoleWriter) {
		w.Out = rl.Stdout()
		w.TimeFormat = time.Stamp
	})).With().Timestamp().Logger()
	if !*debug {
		log = log.Level(zerolog.InfoLevel)
	}
	exzerolog.SetupDefaults(&log)
	client.Log = log

	// marvin always replies in the last room he was mentioned in
	var lastRoomID id.RoomID

	syncer := client.Syncer.(*mautrix.DefaultSyncer)
	syncer.OnEventType(event.EventMessage, func(ctx context.Context, evt *event.Event) {

		// When marvin received an event, the room the event was sent from gets set here
		// This is used for replying within that room
		lastRoomID = evt.RoomID
		rl.SetPrompt(fmt.Sprintf("%s> ", lastRoomID))
		log.Info().
			Str("sender", evt.Sender.String()).
			Str("type", evt.Type.String()).
			Str("id", evt.ID.String()).
			Str("body", evt.Content.AsMessage().Body).
			Msg("Received message")

		body := evt.Content.AsMessage().Body

		// filtering out the synced messages, remarvin only answers messages that are coming in
		// after has has been started, otherwise you could spam `.5` and marvin would spam back
		// which is annoying
		// yes, we have an offset of like 6h
		eventTime := evt.Timestamp + (6 * 60 * 60)
		currentTime := time.Now().UnixMilli()
		if eventTime <= currentTime {
			log.Info().Msg("old msg, not responding")
			return
		}

		// don't want to reply to our own messages!
		if evt.Sender.String() == client.UserID.String() {
			log.Info().Msg("ourself, not responding")
			return
		}

		if body == ".5" {
			line := `five questions huh?
				We usually ask new people here 5 questions for the means of introduction. No personal data wanted. Are you in for that?

				Hi and welcome to milliways.

				For the means of introduction we ask new people 5 questions.

				1. who are you
				2. how did you get here
				3. what can you do for milliways
				4. what can milliways do for you
				5. what are you good in which is not computers

				and bonus question: Do you come to 38c3?
			`
			resp, err := client.SendText(context.TODO(), lastRoomID, line)
			if err != nil {
				log.Error().Err(err).Msg("Failed to send event")
			} else {
				log.Info().Str("event_id", resp.EventID.String()).Msg("Event sent")
			}
		}
	})

	// auto join the room if invited
	syncer.OnEventType(event.StateMember, func(ctx context.Context, evt *event.Event) {
		if evt.GetStateKey() == client.UserID.String() && evt.Content.AsMember().Membership == event.MembershipInvite {
			_, err := client.JoinRoomByID(ctx, evt.RoomID)
			if err == nil {
				lastRoomID = evt.RoomID
				rl.SetPrompt(fmt.Sprintf("%s> ", lastRoomID))
				log.Info().
					Str("room_id", evt.RoomID.String()).
					Str("inviter", evt.Sender.String()).
					Msg("Joined room after invite")
			} else {
				log.Error().Err(err).
					Str("room_id", evt.RoomID.String()).
					Str("inviter", evt.Sender.String()).
					Msg("Failed to join room after invite")
			}
		}

	})

	// The crypto stuff here isn't working
	// Seems like it can't find the olm stuff on my system, due to this bot only running in the
	// public matrix channel and it only sending some questions to all users, this shouldn't be all
	// to much of a problem, yet I'd like to get this working at some point

	// --------------
	//  cryptoHelper, err := cryptohelper.NewCryptoHelper(client, []byte("meow"), *database)
	//  if err != nil {
	//  	panic(err)
	//  }
	// --------------

	// You can also store the user/device IDs and access token and put them in the client beforehand instead of using LoginAs.
	//client.UserID = "..."
	//client.DeviceID = "..."
	//client.AccessToken = "..."
	// You don't need to set a device ID in LoginAs because the crypto helper will set it for you if necessary.

	// --------------
	//  cryptoHelper.LoginAs = &mautrix.ReqLogin{
	//  	Type:       mautrix.AuthTypePassword,
	//  	Identifier: mautrix.UserIdentifier{Type: mautrix.IdentifierTypeUser, User: *username},
	//  	Password:   *password,
	//  }
	// --------------

	// If you want to use multiple clients with the same DB, you should set a distinct database account ID for each one.
	//cryptoHelper.DBAccountID = ""

	// --------------
	//  err = cryptoHelper.Init(context.TODO())
	//  if err != nil {
	//  	panic(err)
	//  }
	// --------------

	// Set the client crypto helper in order to automatically encrypt outgoing messages
	// --------------
	//  client.Crypto = cryptoHelper
	// --------------

	log.Info().Msg("Now running")
	syncCtx, cancelSync := context.WithCancel(context.Background())
	var syncStopWait sync.WaitGroup
	syncStopWait.Add(1)

	go func() {
		err = client.SyncWithContext(syncCtx)
		defer syncStopWait.Done()
		if err != nil && !errors.Is(err, context.Canceled) {
			panic(err)
		}
	}()

	for {
		line, err := rl.Readline()
		if err != nil { // io.EOF
			break
		}
		if lastRoomID == "" {
			log.Error().Msg("Wait for an incoming message before sending messages")
			continue
		}
		resp, err := client.SendText(context.TODO(), lastRoomID, line)
		if err != nil {
			log.Error().Err(err).Msg("Failed to send event")
		} else {
			log.Info().Str("event_id", resp.EventID.String()).Msg("Event sent")
		}
	}
	cancelSync()
	syncStopWait.Wait()
	//  err = cryptoHelper.Close()
	//  if err != nil {
	//  	log.Error().Err(err).Msg("Error closing database")
	//  }
}