Skip to content

Commit

Permalink
feat(discord): support <code-block> (#279)
Browse files Browse the repository at this point in the history
Co-authored-by: Shigma <[email protected]>
  • Loading branch information
yhx-12243 and shigma authored Jun 17, 2024
1 parent b61c1e0 commit f63c7d1
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
12 changes: 8 additions & 4 deletions adapters/discord/src/message.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Context, Dict, h, MessageEncoder, Schema, Universal } from '@satorijs/core'
import { DiscordBot } from './bot'
import { ActionRow, Button, ButtonStyles, Channel, ComponentType, Message } from './types'
import { decodeMessage, sanitize } from './utils'
import { decodeMessage, sanitize, sanitizeCode } from './utils'

type RenderMode = 'default' | 'figure'

Expand Down Expand Up @@ -230,9 +230,13 @@ export class DiscordMessageEncoder<C extends Context = Context> extends MessageE
await this.render(children)
this.buffer += '||'
} else if (type === 'code') {
this.buffer += '`'
await this.render(children)
this.buffer += '`'
this.buffer += '``'
this.buffer += sanitizeCode(children.toString())
this.buffer += '``'
} else if (type === 'code-block') {
this.buffer += `\`\`\`${attrs.language ?? ''}\n`
this.buffer += sanitizeCode(children.toString())
this.buffer += '\n```'
} else if (type === 'a') {
this.buffer += '['
await this.render(children)
Expand Down
4 changes: 4 additions & 0 deletions adapters/discord/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ export const sanitize = (val: string) =>
.replace(/@everyone/g, () => '\\@everyone')
.replace(/@here/g, () => '\\@here')

// discord has no way to escape ` in code/codeblock, so we use zero-width space as a fallback.
// we don't need or have to do any escape other than ` in code/codeblock.
export const sanitizeCode = (val: string) => val.replace(/(?<=`)(?=`)/g, '\u200b')

export const decodeUser = (user: Discord.User): Universal.User => ({
id: user.id,
name: user.username,
Expand Down

0 comments on commit f63c7d1

Please sign in to comment.