Skip to content

Commit

Permalink
Strict typecheck
Browse files Browse the repository at this point in the history
  • Loading branch information
azrsh committed Sep 2, 2022
1 parent 8a531de commit cfacc2c
Show file tree
Hide file tree
Showing 18 changed files with 46 additions and 66 deletions.
24 changes: 13 additions & 11 deletions src/ai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ export default class Ai {
private connection: any
modules: IModule[] = []
private isInterrupted: boolean = false
private invervalPingObj: NodeJS.Timer
meta: any

constructor(account: User, modules: IModule[]) {
Expand All @@ -25,7 +24,7 @@ export default class Ai {
}

private init() {
let loadedModules = []
let loadedModules: IModule[] = []
for (let m of this.modules) {
try {
m.install(this)
Expand All @@ -50,7 +49,7 @@ export default class Ai {
.then((json) => (this.meta = json))
.catch((err) => console.error(err))

this.invervalPingObj = setInterval(() => {
setInterval(() => {
this.connection.send("ping")
if (process.env.DEBUG) console.log("ping from client")
}, moment.duration(1, "minute").asMilliseconds())
Expand Down Expand Up @@ -96,7 +95,7 @@ export default class Ai {
private initConnection() {
this.connection = new ReconnectingWebSocket(config.streamURL, [], {
WebSocket: WebSocket,
connectionTimeout: config.connectionTimeout | 5000,
connectionTimeout: config.connectionTimeout || 5000,
})

this.connection.addEventListener("error", (e) => {
Expand Down Expand Up @@ -205,7 +204,7 @@ export default class Ai {
this.modules
.filter((m) => typeof m.onNote == "function")
.forEach((m) => {
return m.onNote(body)
return m.onNote!(body) // onNote's nullability has been checked
})
}

Expand Down Expand Up @@ -234,19 +233,20 @@ export default class Ai {
`!${msg.user.name}(@${generateUserId(msg.user)}): ${msg.text}`
)
let funcs = this.modules.filter((m) => typeof m.onCommand == "function")
let done: boolean
let done = false
for (let i = 0; i < funcs.length; i++) {
if (done) break
let res = await funcs[i].onCommand(msg, r[1].split(" "))
// onCommand's nullability has been checked
let res = await funcs[i].onCommand!(msg, r[1].split(" "))
if (res === true || typeof res === "object") done = true
}
if (!done) msg.reply("command not found")
} else {
let res: ReturnType<IModule["onMention"]>
let res: ReturnType<NonNullable<IModule["onMention"]>>
this.modules
.filter((m) => typeof m.onMention == "function")
.some((m) => {
res = m.onMention(msg)
res = m.onMention!(msg) // onMention's nullability has been checked
return res === true || typeof res === "object"
})
}
Expand All @@ -260,7 +260,7 @@ export default class Ai {
this.modules
.filter((m) => typeof m.onFollowed == "function")
.forEach((m) => {
return m.onFollowed(user)
return m.onFollowed!(user) // onFollowed's nullability has been checked
})
}

Expand All @@ -269,7 +269,9 @@ export default class Ai {
this.connection.close()
this.modules
.filter((m) => typeof m.onInterrupted == "function")
.forEach((m) => m.onInterrupted())
.forEach((m) => {
m.onInterrupted!() // onInterrupted's nullability has been checked
})
process.exit(0)
}
}
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Ai from "./ai"
import Modulez from "./modules"
import fetch from "node-fetch"
import IModule from "./module"
import { User } from "./misskey"

console.log(">>> starting... <<<")

Expand All @@ -15,7 +16,7 @@ async function main() {
}),
headers: config.headers,
})
let me = await tmp.json()
let me = (await tmp.json()) as User // Force convert to misskey.User
console.log(`I am ${me.name}(@${me.username})!`)
console.log(`Version: ${config.version}(${config.revision})`)
me.host = config.host
Expand Down
2 changes: 1 addition & 1 deletion src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export default interface IModule {
name: string
priority: number
commands?: Array<ICommand>
install?: (ai: Ai) => void
install: (ai: Ai) => void
onMention?: (msg: MessageLike) => boolean
onNote?: (note: any) => void
onFollowed?: (user: User) => void
Expand Down
4 changes: 2 additions & 2 deletions src/modules/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export default class AdminModule implements IModule {
desc: "Shutdown the bot",
},
]
private ai: Ai
private ai!: Ai

public install(ai: Ai) {
this.ai = ai
Expand All @@ -41,7 +41,7 @@ Version: ${config.version}(${config.revision})
`
res += this.ai.modules
.filter((i) => typeof i.info == "function")
.map((i) => i.info())
.map((i) => i.info!()) // info's nullability has been checked
.join("\n")
res += "\n```"
msg.reply(res)
Expand Down
4 changes: 2 additions & 2 deletions src/modules/auto-follow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { User } from "../misskey"
export default class AutoFollowModule implements IModule {
public readonly priority = 0
public readonly name = "autoFollow"
private ai: Ai
private ai!: Ai

public install(ai: Ai) {
this.ai = ai
Expand All @@ -21,7 +21,7 @@ export default class AutoFollowModule implements IModule {
const res = await this.ai.api("following/create", {
userId: user.id,
})
const json = await res.json()
const json = (await res.json()) as { error?: unknown } // Force convert to { error?: unknown }
if (json.error)
console.log(`Following ${user.name}(@${user.username}): ${json.error}`)
else console.log(`Followed user ${user.name}(@${user.username})`)
Expand Down
7 changes: 2 additions & 5 deletions src/modules/dice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,8 @@ export default class DiceModule implements IModule {
desc: "3d6 -> /dice 3 6",
},
]
private ai: Ai

public install(ai: Ai) {
this.ai = ai
}
public install(_: Ai) {}

public async onCommand(msg: MessageLike, cmd: string[]): Promise<boolean> {
if (cmd[0] == "dice") {
Expand All @@ -35,7 +32,7 @@ export default class DiceModule implements IModule {
msg.reply("Argument is invalid. (amount > 0, max > 0, amount <= 500)")
return true
}
let res = []
let res: number[] = []
for (let i = 0; i < amount; i++) {
res.push(Math.ceil(Math.random() * m))
}
Expand Down
2 changes: 1 addition & 1 deletion src/modules/emoji-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export default class EmojiListModule implements IModule {
desc: "Display all the emojis registered in the instance.",
},
]
private ai: Ai
private ai!: Ai

public install(ai: Ai) {
this.ai = ai
Expand Down
5 changes: 1 addition & 4 deletions src/modules/greeting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,8 @@ import MessageLike from "../message-like"
export default class GreetingModule implements IModule {
public readonly priority = 2
public readonly name = "greeting"
private ai: Ai

public install(ai: Ai) {
this.ai = ai
}
public install(_: Ai) {}

public onMention(msg: MessageLike) {
if (!msg.text) return false
Expand Down
6 changes: 3 additions & 3 deletions src/modules/kakariuke-graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default class KakariukeGraphModule implements IModule {
desc: "Generate a directed graph for kakariuke(Ja)",
},
]
private ai: Ai
private ai!: Ai

public install(ai: Ai) {
this.ai = ai
Expand Down Expand Up @@ -69,11 +69,11 @@ export default class KakariukeGraphModule implements IModule {
})

if (msg.isMessage) {
msg.reply("描画しました!", null, {
msg.reply("描画しました!", undefined, {
fileId: imageRes.id,
})
} else
msg.reply("描画しました!!", null, {
msg.reply("描画しました!!", undefined, {
fileIds: [imageRes.id],
})
}
Expand Down
11 changes: 5 additions & 6 deletions src/modules/markov-speaking/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,10 @@ export default class MarkovSpeakingModule implements IModule {
desc: "Remove chains containing specified morphemes",
},
]
private ai: Ai
private ai!: Ai
private markov: any
private database: IDatabase
private intervalObj: NodeJS.Timer
private filter: WordFilter
private database!: IDatabase
private filter!: WordFilter

private get sentenceLength(): number {
function getRandomInt(max) {
Expand Down Expand Up @@ -58,14 +57,14 @@ export default class MarkovSpeakingModule implements IModule {
if (duration == 0) {
console.error("Bad duration setting. intervalPost feature is disabled.")
}
this.intervalObj = setInterval(async () => {
setInterval(async () => {
let text = ""
text += this.markov.generate(this.sentenceLength).join("\n")
let res = await this.ai.api("notes/create", {
text: text,
visibility: config.visibility,
})
let json = await res.json()
const json = (await res.json()) as { error?: unknown } // Force convert to { error?: unknown }
if (json.error) {
console.error("An error occured while creating the interval post")
console.error(`content: ${text}`)
Expand Down
8 changes: 4 additions & 4 deletions src/modules/markov-speaking/word-filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import * as fs from "fs"
export default class WordFilter {
private filterURL: string
private initialized: boolean = false
public ngwordDict: string[]
public okwordDict: string[]
public ngwordDict: string[] = []
public okwordDict: string[] = []

constructor() {
this.filterURL = config.markovSpeaking.wordFilterURL
Expand Down Expand Up @@ -86,7 +86,7 @@ export default class WordFilter {
let ok: boolean = false
for (let okword of this.okwordDict) {
if (str.length - k < okword.length) break
if (str.substr(k, okword.length) == okword) {
if (str.slice(k, k + okword.length) == okword) {
k += okword.length
ok = true
break
Expand All @@ -96,7 +96,7 @@ export default class WordFilter {

for (let ngword of this.ngwordDict) {
if (str.length - k < ngword.length) break
if (str.substr(k, ngword.length) == ngword) {
if (str.slice(k, k + ngword.length) == ngword) {
if (config.markovSpeaking.wordFilterLog) console.log(`*B: ${ngword}`)
return true
}
Expand Down
9 changes: 4 additions & 5 deletions src/modules/math.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import IModule from "../module"
import MessageLike from "../message-like"
import Ai from "../ai"
import { User } from "../misskey"
import config from "../config"
const asciimathToLaTeX = require("asciimath-to-latex")
const mj = require("mathjax-node")
Expand All @@ -24,9 +23,9 @@ export default class MathModule implements IModule {
desc: "Render LaTeX or AsciiMath to .png file",
},
]
private ai: Ai
private ai!: Ai
public size!: number

public size: number
public install(ai: Ai) {
this.ai = ai
this.size = config.math.size
Expand Down Expand Up @@ -86,11 +85,11 @@ export default class MathModule implements IModule {
}

if (msg.isMessage) {
msg.reply("Rendered!", null, {
msg.reply("Rendered!", undefined, {
fileId: file.id,
})
} else
msg.reply("Rendered! Here it is", null, {
msg.reply("Rendered! Here it is", undefined, {
fileIds: [file.id],
})
break
Expand Down
5 changes: 1 addition & 4 deletions src/modules/othello-redirect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,8 @@ import MessageLike from "../message-like"
export default class OthelloRedirectModule implements IModule {
public readonly name = "othelloRedirect"
public readonly priority = 2
private ai: Ai

public install(ai: Ai) {
this.ai = ai
}
public install(_: Ai) {}

public onMention(msg: MessageLike): boolean {
if (msg.text.match(/(||othello|reversi|Othello|Reversi)/)) {
Expand Down
5 changes: 1 addition & 4 deletions src/modules/ping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,8 @@ export default class PingModule implements IModule {
name: "ping",
},
]
private ai: Ai

public install(ai: Ai) {
this.ai = ai
}
public install(_: Ai) {}

public async onCommand(msg: MessageLike, cmd: string[]): Promise<boolean> {
if (cmd[0] == "ping") {
Expand Down
5 changes: 1 addition & 4 deletions src/modules/random-choice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,8 @@ export default class RandomChoiceModule implements IModule {
desc: "choose one from given N choices",
},
]
private ai: Ai

public install(ai: Ai) {
this.ai = ai
}
public install(_: Ai) {}

public async onCommand(msg: MessageLike, cmd: string[]): Promise<boolean> {
if (cmd[0] == "choose") {
Expand Down
6 changes: 1 addition & 5 deletions src/modules/suru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,7 @@ export default class SuruModule implements IModule {
},
]

private ai: Ai

public install(ai: Ai) {
this.ai = ai
}
public install(_: Ai) {}

public async onCommand(msg: MessageLike, cmd: string[]): Promise<boolean> {
if (cmd[0] == "suru") {
Expand Down
5 changes: 1 addition & 4 deletions src/modules/sushi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,8 @@ import MessageLike from "../message-like"
export default class SushiModule implements IModule {
public readonly priority = 2
public readonly name = "sushi"
private ai: Ai

public install(ai: Ai) {
this.ai = ai
}
public install(_: Ai) {}

public onMention(msg: MessageLike) {
if (!msg.text) return false
Expand Down
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"compilerOptions": {
"strict": true,
"noEmitOnError": true,
"noImplicitAny": false,
"noImplicitReturns": true,
Expand Down

0 comments on commit cfacc2c

Please sign in to comment.