Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(discord): support <code-block> #279

Merged
merged 3 commits into from
Jun 17, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 === 'codeblock') {
shigma marked this conversation as resolved.
Show resolved Hide resolved
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
6 changes: 6 additions & 0 deletions adapters/discord/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ export const sanitize = (val: string) =>
.replace(/@everyone/g, () => '\\@everyone')
.replace(/@here/g, () => '\\@here')

export const sanitizeCode = (val: string) =>
val
.replace(/(?<=`)(?=`)/g, '\u200b')
// 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.
shigma marked this conversation as resolved.
Show resolved Hide resolved

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