-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
327 lines (289 loc) · 7.13 KB
/
main.go
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package main
import (
"bytes"
"context"
_ "embed"
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"net/http"
"os"
"regexp"
"strings"
"sync"
"time"
//"github.com/ikawaha/kagome-dict/uni"
//"github.com/ikawaha/kagome-dict/ipa"
"github.com/ikawaha/kagome-dict-ipa-neologd"
"github.com/ikawaha/kagome-dict/dict"
"github.com/mattn/go-haiku"
"github.com/nbd-wtf/go-nostr"
"github.com/nbd-wtf/go-nostr/nip19"
)
const name = "nostr-haikubot"
const version = "0.0.60"
var revision = "HEAD"
var (
//feedRelay = "wss://universe.nostrich.land/?lang=ja"
feedRelays = []string{
"wss://relay-jp.nostr.wirednet.jp",
"wss://yabu.me",
}
postRelays = []string{
//"wss://nostr-relay.nokotaro.com",
"wss://relay-jp.nostr.wirednet.jp",
"wss://yabu.me",
//"wss://nostr.holybea.com",
//"wss://relay.snort.social",
"wss://relay.damus.io",
//"wss://relay.nostrich.land",
//"wss://nostr.h3z.jp",
}
nsec string
sk string
pub string
reLink = regexp.MustCompile(`\b\w+://\S+\b`)
reTag = regexp.MustCompile(`\B#\S+`)
reJapanese = regexp.MustCompile(`[0-9A-Za-zぁ-ゖァ-ヾ一-鶴]`)
debug = false
kagomeDic = ipaneologd.Dict()
//go:embed userdic.txt
dicdata []byte
userDic *dict.UserDict
)
func init() {
time.Local = time.FixedZone("Local", 9*60*60)
r, err := dict.NewUserDicRecords(bytes.NewReader(dicdata))
if err != nil {
panic(err.Error())
}
userDic, err = r.NewUserDict()
if err != nil {
panic(err.Error())
}
nsec = os.Getenv("HAIKUBOT_NSEC")
if nsec == "" {
panic("HAIKUBOT_NSEC is not set")
}
if _, s, err := nip19.Decode(nsec); err == nil {
sk, _ = s.(string)
} else {
panic(err.Error())
}
if pub, err := nostr.GetPublicKey(sk); err == nil {
if _, err := nip19.EncodePublicKey(pub); err != nil {
panic(err.Error())
}
} else {
panic(err.Error())
}
}
func replyEvent(rs []string, evv *nostr.Event, content string) error {
ev := nostr.Event{}
ev.PubKey = pub
ev.CreatedAt = nostr.Timestamp(evv.CreatedAt.Time().Add(time.Second).Unix())
ev.Kind = evv.Kind
ev.Content = content
ev.Tags = ev.Tags.AppendUnique(nostr.Tag{"e", evv.ID, "", "reply"})
ev.Tags = ev.Tags.AppendUnique(nostr.Tag{"p", evv.PubKey})
ev.Sign(sk)
success := 0
for _, r := range rs {
relay, err := nostr.RelayConnect(context.Background(), r)
if err != nil {
continue
}
if relay.Publish(context.Background(), ev) == nil {
success++
}
relay.Close()
}
if success == 0 {
return errors.New("failed to publish")
}
return nil
}
func postEvent(rs []string, evv *nostr.Event, content string, tag string) error {
ev := nostr.Event{}
ev.PubKey = pub
ev.CreatedAt = nostr.Timestamp(evv.CreatedAt.Time().Add(time.Second).Unix())
ev.Kind = evv.Kind
if ev.Kind == nostr.KindTextNote {
if nevent, err := nip19.EncodeEvent(evv.ID, rs, evv.PubKey); err == nil {
ev.Content = content + " " + tag + "\nnostr:" + nevent
} else {
ev.Content = "#[0]\n" + content + " " + tag
}
ev.Tags = ev.Tags.AppendUnique(nostr.Tag{"e", evv.ID, "", "mention"})
} else {
ev.Content = content + " " + tag
ev.Tags = ev.Tags.AppendUnique(nostr.Tag{"e", evv.ID, "", "reply"})
for _, tag := range evv.Tags.FilterOut([]string{"e", "p"}) {
ev.Tags = ev.Tags.AppendUnique(tag)
}
}
ev.Sign(sk)
success := 0
for _, r := range rs {
relay, err := nostr.RelayConnect(context.Background(), r)
if err != nil {
continue
}
if relay.Publish(context.Background(), ev) == nil {
success++
}
relay.Close()
}
if success == 0 {
return errors.New("failed to publish")
}
return nil
}
func normalize(s string) string {
s = reLink.ReplaceAllString(s, "")
s = reTag.ReplaceAllString(s, "")
return strings.TrimSpace(s)
}
func isHaiku(s string) bool {
return haiku.MatchWithOpt(s, []int{5, 7, 5}, &haiku.Opt{Dict: kagomeDic, UserDict: userDic, Debug: debug})
}
func isTanka(s string) bool {
return haiku.MatchWithOpt(s, []int{5, 7, 5, 7, 7}, &haiku.Opt{Dict: kagomeDic, UserDict: userDic, Debug: debug})
}
func analyze(ev *nostr.Event) error {
if ev.PubKey == pub || strings.Contains(ev.Content, "#n575") || !reJapanese.MatchString(ev.Content) {
return nil
}
content := normalize(ev.Content)
if isHaiku(content) {
log.Println("MATCHED HAIKU!", content)
err := postEvent(postRelays, ev, content, "#n575 #haiku")
if err != nil {
return err
}
}
if isTanka(content) {
log.Println("MATCHED TANKA!", content)
err := postEvent(postRelays, ev, content, "#n57577 #tanka")
if err != nil {
return err
}
}
return nil
}
func heartbeatPush(url string) {
resp, err := http.Get(url)
if err != nil {
log.Println(err.Error())
return
}
defer resp.Body.Close()
}
func server(from *time.Time) {
enc := json.NewEncoder(os.Stdout)
log.Println("Connecting to relay")
pool := nostr.NewSimplePool(context.Background())
events := make(chan *nostr.Event, 100)
timestamp := nostr.Timestamp(from.Unix())
filters := []nostr.Filter{{
Kinds: []int{nostr.KindTextNote, nostr.KindChannelMessage},
Since: ×tamp,
}}
sub := pool.SubMany(context.Background(), feedRelays, filters)
hbtimer := time.NewTicker(5 * time.Minute)
defer hbtimer.Stop()
var wg sync.WaitGroup
wg.Add(1)
go func(wg *sync.WaitGroup, events chan *nostr.Event) {
defer wg.Done()
log.Println("Start")
events_loop:
for {
select {
case ev, ok := <-events:
if !ok {
break events_loop
}
enc.Encode(ev)
if ev.PubKey == pub {
continue
}
for _, v := range ev.Tags {
if len(v) >= 2 && v[0] == "t" && v[1] == "俳句チェック" {
s := normalize(ev.Content)
var buf bytes.Buffer
haiku.MatchWithOpt(s, []int{5, 7, 5}, &haiku.Opt{Dict: kagomeDic, UserDict: userDic, Debug: true, DebugWriter: &buf})
err := replyEvent(postRelays, ev, buf.String())
if err != nil {
log.Println(err)
}
continue events_loop
}
if len(v) >= 2 && v[0] == "t" && v[1] == "短歌チェック" {
s := normalize(ev.Content)
var buf bytes.Buffer
haiku.MatchWithOpt(s, []int{5, 7, 5, 7, 7}, &haiku.Opt{Dict: kagomeDic, UserDict: userDic, Debug: true, DebugWriter: &buf})
err := replyEvent(postRelays, ev, buf.String())
if err != nil {
log.Println(err)
}
continue events_loop
}
}
err := analyze(ev)
if err != nil {
log.Println(err)
continue
}
if ev.CreatedAt.Time().After(*from) {
*from = ev.CreatedAt.Time()
}
case <-hbtimer.C:
if url := os.Getenv("HEARTBEAT_URL"); url != "" {
go heartbeatPush(url)
}
}
}
log.Println("Finish")
}(&wg, events)
log.Println("Subscribing events")
loop:
for {
ev, ok := <-sub
if !ok {
break loop
}
events <- ev.Event
}
wg.Wait()
log.Println("Stopped")
}
func main() {
var ver bool
var tt bool
flag.BoolVar(&debug, "V", false, "verbose")
flag.BoolVar(&ver, "version", false, "show version")
flag.BoolVar(&tt, "t", false, "test")
flag.Parse()
if ver {
fmt.Println(version)
os.Exit(0)
}
if tt {
s := normalize(strings.Join(flag.Args(), " "))
fmt.Println(s)
if isHaiku(s) {
fmt.Println("HAIKU!")
} else if isTanka(s) {
fmt.Println("TANKA!")
}
return
}
from := time.Now()
for {
server(&from)
time.Sleep(5 * time.Second)
}
}