move out src/test to test

This commit is contained in:
DjDeveloperr 2021-04-04 11:22:47 +05:30
parent f812e06d17
commit 46cbd66166
26 changed files with 51 additions and 45 deletions

27
test/chunk.ts Normal file
View file

@ -0,0 +1,27 @@
import { Client, Intents } from '../mod.ts'
import { TOKEN } from './config.ts'
const client = new Client()
client.on('debug', console.log)
client.on('ready', () => {
console.log(`Logged in as ${client.user?.tag}!`)
})
client.on('guildLoaded', async (guild) => {
if (guild.id !== '783319033205751809') return
const arr = await guild.channels.array()
console.log(arr.length)
guild
.chunk({ presences: true }, true)
.then((guild) => {
console.log(`Chunked guild:`, guild.id)
})
.catch((e) => {
console.log(`Failed to Chunk: ${guild.id} - ${e}`)
})
})
console.log('Connecting...')
client.connect(TOKEN, Intents.All)

70
test/class.ts Normal file
View file

@ -0,0 +1,70 @@
import {
CommandClient,
event,
Intents,
command,
CommandContext,
Extension,
CommandBuilder
} from '../mod.ts'
import { TOKEN } from './config.ts'
class MyClient extends CommandClient {
constructor() {
super({
prefix: ['!', '!!'],
caseSensitive: false
})
}
@event()
ready(): void {
console.log(`Logged in as ${this.user?.tag}!`)
}
@command({ aliases: 'pong' })
Ping(ctx: CommandContext): void {
ctx.message.reply('Pong!')
}
}
class VCExtension extends Extension {
name = 'VC'
subPrefix = 'vc'
@command()
async join(ctx: CommandContext): Promise<void> {
const userVS = await ctx.guild?.voiceStates.get(ctx.author.id)
if (userVS === undefined) {
ctx.message.reply("You're not in VC.")
return
}
await userVS.channel?.join()
ctx.message.reply(`Joined VC channel - ${userVS.channel?.name}!`)
}
@command()
async leave(ctx: CommandContext): Promise<void> {
const userVS = await ctx.guild?.voiceStates.get(
(ctx.client.user?.id as unknown) as string
)
if (userVS === undefined) {
ctx.message.reply("I'm not in VC.")
return
}
userVS.channel?.leave()
ctx.message.reply(`Left VC channel - ${userVS.channel?.name}!`)
}
}
const client = new MyClient()
client.extensions.load(VCExtension)
client.commands.add(
new CommandBuilder()
.setName('join')
.onExecute((ctx) => ctx.message.reply('haha'))
)
client.connect(TOKEN, Intents.All)

154
test/cmd.ts Normal file
View file

@ -0,0 +1,154 @@
import {
Command,
CommandClient,
Intents,
CommandContext,
Extension,
GuildChannels,
Invite
} from '../mod.ts'
import { TOKEN } from './config.ts'
const client = new CommandClient({
prefix: ['pls', '!'],
spacesAfterPrefix: true,
mentionPrefix: true,
owners: ['422957901716652033']
})
client.on('debug', console.log)
client.on('ready', () => {
console.log(`[Login] Logged in as ${client.user?.tag}!`)
})
client.on('messageDelete', (msg) => {
console.log(`Message Deleted: ${msg.id}, ${msg.author.tag}, ${msg.content}`)
})
client.on('messageUpdate', (before, after) => {
console.log('Message Update')
console.log(`Before: ${before.author.tag}: ${before.content}`)
console.log(`After: ${after.author.tag}: ${after.content}`)
})
client.on('guildMemberAdd', (member) => {
console.log(`Member Join: ${member.user.tag}`)
})
client.on('guildMemberRemove', (member) => {
console.log(`Member Leave: ${member.user.tag}`)
})
client.on('guildRoleCreate', (role) => {
console.log(`Role Create: ${role.name}`)
})
client.on('guildRoleDelete', (role) => {
console.log(`Role Delete: ${role.name}`)
})
client.on('guildRoleUpdate', (role, after) => {
console.log(`Role Update: ${role.name}, ${after.name}`)
})
client.on('guildIntegrationsUpdate', (guild) => {
console.log(`Guild Integrations Update: ${guild.name}`)
})
client.on('webhooksUpdate', (guild, channel) => {
console.log(`Webhooks Updated in #${channel.name} from ${guild.name}`)
})
client.on('commandError', console.error)
client.on('inviteCreate', (invite: Invite) => {
console.log(`Invite Create: ${invite.code}`)
})
client.on('inviteDelete', (invite: Invite) => {
console.log(`Invite Delete: ${invite.code}`)
})
client.on('inviteDeleteUncached', (invite) => {
console.log(invite)
})
client.on('commandError', console.error)
class ChannelLog extends Extension {
onChannelCreate(ext: Extension, channel: GuildChannels): void {
console.log(`Channel Created: ${channel.name}`)
}
load(): void {
this.listen('channelCreate', this.onChannelCreate)
class Pong extends Command {
name = 'Pong'
execute(ctx: CommandContext): any {
ctx.message.reply('Ping!')
}
}
this.commands.add(Pong)
}
}
client.extensions.load(ChannelLog)
client.on('messageDeleteBulk', (channel, messages, uncached) => {
console.log(
`=== Message Delete Bulk ===\nMessages: ${messages
.map((m) => m.id)
.join(', ')}\nUncached: ${[...uncached.values()].join(', ')}`
)
})
client.on('channelUpdate', (before, after) => {
console.log(
`Channel Update: ${(before as GuildChannels).name}, ${
(after as GuildChannels).name
}`
)
})
client.on('voiceStateAdd', (state) => {
console.log('VC Join', state.user.tag)
})
client.on('voiceStateRemove', (state) => {
console.log('VC Leave', state.user.tag)
})
client.on('messageReactionAdd', (reaction, user) => {
console.log(`${user.tag} reacted with ${reaction.emoji.name}`)
})
client.on('messageReactionRemove', (reaction, user) => {
console.log(`${user.tag} removed reaction ${reaction.emoji.name}`)
})
client.on('messageReactionRemoveEmoji', (message, emoji) => {
console.log(`All ${emoji.name} emoji reactions removed from ${message.id}`)
})
client.on('messageReactionRemoveAll', (message) => {
console.log(`All reactions remove from Message: ${message.id}`)
})
// client.on('raw', (evt: string) => console.log(`EVENT: ${evt}`))
const files = Deno.readDirSync('cmds')
for (const file of files) {
const module = await import(`./cmds/${file.name}`)
// eslint-disable-next-line new-cap
const cmd = new module.default()
client.commands.add(cmd)
console.log(`Loaded command ${cmd.name}!`)
}
console.log(`Loaded ${client.commands.count} commands!`)
client.connect(TOKEN, Intents.create(['GUILD_MEMBERS', 'GUILD_PRESENCES']))

26
test/cmds/addemoji.ts Normal file
View file

@ -0,0 +1,26 @@
import { Command, CommandContext } from '../../mod.ts'
export default class AddEmojiCommand extends Command {
name = 'addemoji'
aliases = ['ae', 'emojiadd']
args = 2
guildOnly = true
execute(ctx: CommandContext): any {
const name = ctx.args[0]
if (name === undefined) return ctx.message.reply('No name was given!')
const url = ctx.argString.slice(name.length).trim()
if (url === '') return ctx.message.reply('No URL was given!')
ctx.message.guild?.emojis
.create(name, url)
.then((emoji) => {
if (emoji === undefined) throw new Error('Unknown')
ctx.message.reply(
`Successfully added emoji ${emoji.toString()} ${emoji.name}!`
)
})
.catch((e) => {
ctx.message.reply(`Failed to add emoji. Reason: ${e.message}`)
})
}
}

20
test/cmds/eval.ts Normal file
View file

@ -0,0 +1,20 @@
import { Command, CommandContext } from '../../mod.ts'
export default class EvalCommand extends Command {
name = 'eval'
ownerOnly = true
async execute(ctx: CommandContext): Promise<void> {
try {
// eslint-disable-next-line no-eval
let evaled = eval(ctx.argString)
if (evaled instanceof Promise) evaled = await evaled
if (typeof evaled === 'object') evaled = Deno.inspect(evaled)
await ctx.message.reply(
`\`\`\`js\n${`${evaled}`.substring(0, 1990)}\n\`\`\``
)
} catch (e) {
ctx.message.reply(`\`\`\`js\n${e.stack}\n\`\`\``)
}
}
}

16
test/cmds/join.ts Normal file
View file

@ -0,0 +1,16 @@
import { Command, CommandContext } from '../../mod.ts'
export default class JoinCommand extends Command {
name = 'join'
guildOnly = true
async execute(ctx: CommandContext): Promise<void> {
const userVS = await ctx.guild?.voiceStates.get(ctx.author.id)
if (userVS === undefined) {
ctx.message.reply("You're not in VC.")
return
}
await userVS.channel?.join()
ctx.message.reply(`Joined VC channel - ${userVS.channel?.name}!`)
}
}

View file

@ -0,0 +1,26 @@
import {
Command,
CommandContext,
ChannelTypes,
VoiceChannel
} from '../../mod.ts'
export default class KickFromSpecificVoiceCommand extends Command {
name = 'kickFromSpecificVoice'
async execute(ctx: CommandContext): Promise<void> {
if (ctx.guild !== undefined) {
const channel = await ctx.guild.channels.get('YOUR VOICE CHANNEL ID')
if (channel === undefined || channel.type !== ChannelTypes.GUILD_VOICE) {
ctx.channel.send('The channel is either not a voice or not available.')
return
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const members = await (channel as VoiceChannel).disconnectAll()
members.forEach((member) => {
ctx.channel.send(`Kicked member ${member.id}`)
})
}
}
}

View file

@ -0,0 +1,19 @@
import { Command, CommandContext } from '../../mod.ts'
export default class KickFromVoiceCommand extends Command {
name = 'kickFromVoice'
async execute(ctx: CommandContext): Promise<void> {
if (ctx.guild !== undefined) {
const voiceStates = await ctx.guild.voiceStates.array()
if (voiceStates !== undefined) {
voiceStates.forEach(async (voiceState) => {
const member = await voiceState.disconnect()
if (member !== undefined) {
ctx.channel.send(`Kicked member ${member.id}`)
}
})
}
}
}
}

18
test/cmds/leave.ts Normal file
View file

@ -0,0 +1,18 @@
import { Command, CommandContext } from '../../mod.ts'
export default class LeaveCommand extends Command {
name = 'leave'
guildOnly = true
async execute(ctx: CommandContext): Promise<void> {
const userVS = await ctx.guild?.voiceStates.get(
(ctx.client.user?.id as unknown) as string
)
if (userVS === undefined) {
ctx.message.reply("I'm not in VC.")
return
}
userVS.channel?.leave()
ctx.message.reply(`Left VC channel - ${userVS.channel?.name}!`)
}
}

35
test/cmds/mentions.ts Normal file
View file

@ -0,0 +1,35 @@
import { Command, CommandContext, Embed } from '../../mod.ts'
export default class PingCommand extends Command {
name = 'mentions'
aliases = ['m']
execute(ctx: CommandContext): void {
const embed = new Embed()
.setTitle('Mentions')
.addField(
'Users',
`${
ctx.message.mentions.users.size === 0 ? `None` : ''
}${ctx.message.mentions.users.map((u) => u.toString()).join(', ')}`
)
.addField(
'Channels',
`${
ctx.message.mentions.channels.size === 0 ? `None` : ''
}${ctx.message.mentions.channels.map((u) => u.toString()).join(', ')}`
)
.addField(
'Roles',
`${
ctx.message.mentions.roles.size === 0 ? `None` : ''
}${ctx.message.mentions.roles.map((u) => u.toString()).join(', ')}`
)
.addField(
'Everyone?',
ctx.message.mentions.everyone === true ? 'Yes' : 'No'
)
.setColor(0xff0000)
ctx.message.channel.send(embed)
}
}

10
test/cmds/ping.ts Normal file
View file

@ -0,0 +1,10 @@
import { Command, CommandContext } from '../../mod.ts'
export default class PingCommand extends Command {
name = 'ping'
execute(ctx: CommandContext): void {
console.log(ctx.args, ctx.argString)
ctx.message.reply(`Pong! Latency: ${ctx.client.ping}ms`)
}
}

23
test/cmds/userinfo.ts Normal file
View file

@ -0,0 +1,23 @@
import { Command, Member, CommandContext, Embed } from '../../mod.ts'
export default class UserinfoCommand extends Command {
name = 'userinfo'
guildOnly = true
aliases = ['u', 'user']
async execute(ctx: CommandContext): Promise<void> {
const member: Member = ctx.message.member as any
const roles = await member.roles.array()
const embed = new Embed()
.setTitle(`User Info`)
.setAuthor({ name: member.user.tag })
.addField('ID', member.id)
.addField('Roles', roles.map((r) => r.name).join(', '))
.addField(
'Permissions',
JSON.stringify(member.permissions.has('ADMINISTRATOR'))
)
.setColor(0xff00ff)
ctx.channel.send(embed)
}
}

2
test/config.ts.sample Normal file
View file

@ -0,0 +1,2 @@
export const TOKEN = ''
export const WEBHOOK = ''

30
test/debug.ts Normal file
View file

@ -0,0 +1,30 @@
import { Client, event } from '../mod.ts'
import { TOKEN } from './config.ts'
class MyClient extends Client {
constructor() {
super({
token: TOKEN,
intents: []
})
}
@event()
ready(): void {
console.log('Connected!')
}
debug(title: string, msg: string): void {
console.log(`[${title}] ${msg}`)
if (title === 'Gateway' && msg === 'Initializing WebSocket...') {
try {
throw new Error('Stack')
} catch (e) {
console.log(e.stack)
}
}
}
}
const client = new MyClient()
client.connect()

137
test/guild.ts Normal file
View file

@ -0,0 +1,137 @@
import {
Client,
Intents
// Verification
// PermissionFlags,
// ChannelTypes,
// GuildCreateOptions
} from '../mod.ts'
import { TOKEN } from './config.ts'
const client = new Client()
// client.on('guildLoaded', async (guild) => {
// if (guild.name === 'OH WOW') {
// guild.delete()
// }
// })
// client.on('ready', async () => {
// await new Promise((resolve, reject) => setTimeout(resolve, 1000))
// const body: GuildCreateOptions = {
// name: 'OH WOW',
// icon: 'https://helloyunho.xyz/_dist_/images/avatar.png',
// verificationLevel: Verification.NONE,
// roles: [
// {
// id: '1',
// name: 'a role',
// color: 0x103021,
// hoist: false,
// permissions: PermissionFlags.ADMINISTRATOR.toString(),
// mentionable: true
// }
// ],
// channels: [
// {
// name: 'fucking-awesome',
// type: ChannelTypes.GUILD_TEXT,
// id: '1'
// }
// ],
// systemChannelID: '1'
// }
// const guild = await client.guilds.create(body)
// const channels = await guild.channels.array()
// console.log(channels.length)
// const invite = await guild.invites.create(channels[0].id)
// console.log(invite.link)
// })
// client.on('guildLoaded', async (guild) => {
// if (guild.id === 'GUILD_ID') {
// // const roles = await guild.roles.array()
// // if (roles.length > 0) {
// // roles.forEach(async (role) => {
// // if (role.name !== '@everyone') {
// // role.addTo('USER_ID')
// // }
// // })
// // }
// // guild.edit({
// // name: 'OH BOI',
// // verificationLevel: Verification.MEDIUM
// // })
// // const role1 = await guild.roles.create({
// // name: 'IDK1'
// // })
// // const role2 = await guild.roles.create({
// // name: 'IDK2'
// // })
// // alert()
// // await guild.roles.editPositions(
// // {
// // id: role1.id,
// // position: 1
// // },
// // {
// // id: role2.id,
// // position: 2
// // }
// // )
// // alert()
// // role1.delete()
// // role2.delete()
// // const role = await guild.roles.create({
// // name: 'IDK'
// // })
// // alert()
// // await role.edit({
// // name: 'DUMB'
// // })
// // alert()
// // console.log(
// // await guild.getPruneCount({
// // days: 7,
// // includeRoles: ['ROLE_ID']
// // })
// // )
// // console.log(
// // await guild.prune({
// // days: 7,
// // includeRoles: ['ROLE_ID']
// // })
// // )
// // console.log(
// // await guild.prune({
// // days: 7,
// // computePruneCount: false,
// // includeRoles: ['ROLE_ID']
// // })
// // )
// // await guild.editWidget({
// // enabled: true,
// // channel: 'CHANNEL_ID'
// // })
// // console.log(await guild.getWidget())
// // console.log(await guild.getVanity())
// // console.log(await guild.getWidgetImageURL())
// }
// })
client.connect(TOKEN, Intents.All)

11
test/hook.ts Normal file
View file

@ -0,0 +1,11 @@
import { Webhook } from '../mod.ts'
import { WEBHOOK } from './config.ts'
const webhook = await Webhook.fromURL(WEBHOOK)
console.log('Fetched webhook!')
webhook
.send('Hello World', {
name: 'OwO'
})
.then(() => 'Sent message!')

299
test/index.ts Normal file
View file

@ -0,0 +1,299 @@
import {
Client,
Intents,
Message,
Member,
Role,
GuildChannels,
Embed,
Guild,
EveryChannelTypes,
ChannelTypes,
GuildTextChannel,
checkGuildTextBasedChannel,
Permissions,
Collector,
MessageAttachment,
OverrideType
} from '../mod.ts'
import { TOKEN } from './config.ts'
const client = new Client({
// clientProperties: {
// browser: 'Discord iOS'
// }
// bot: false,
// cache: new RedisCacheAdapter({
// hostname: '127.0.0.1',
// port: 6379
// }), // Defaults to in-memory Caching
// shardCount: 2
})
client.on('ready', () => {
console.log(`[Login] Logged in as ${client.user?.tag}!`)
})
client.on('debug', console.log)
client.on('channelUpdate', (b: EveryChannelTypes, a: EveryChannelTypes) => {
if (b.type === ChannelTypes.GUILD_TEXT) {
const before = (b as unknown) as GuildTextChannel
const after = (a as unknown) as GuildTextChannel
before.send('', {
embed: new Embed({
title: 'Channel Update',
description: `Name Before: ${before.name}\nName After: ${after.name}`
})
})
}
})
client.on('messageCreate', async (msg: Message) => {
if (msg.author.bot === true) return
if (msg.stickers !== undefined) {
console.log(
`${msg.author.tag}: (Sticker)${msg.stickers.map(
(sticker) => `Name: ${sticker.name}, Tags: ${sticker.tags}`
)}`
)
} else {
console.log(`${msg.author.tag}: ${msg.content}`)
}
if (msg.content === '!ping') {
msg.reply(`Pong! Ping: ${client.ping}ms`)
} else if (msg.content === '!members') {
const col = await msg.guild?.members.array()
const data = col
?.map((c: Member, i: number) => {
return `${i + 1}. ${c.user.tag}`
})
.join('\n') as string
msg.channel.send('Member List:\n' + data)
} else if (msg.content === '!guilds') {
const guilds = await msg.client.guilds.collection()
msg.channel.send(
'Guild List:\n' +
(guilds
.array()
.map((c: Guild, i: number) => {
return `${i + 1}. ${c.name} - ${c.memberCount} members`
})
.join('\n') as string)
)
} else if (msg.content === '!roles') {
const col = await msg.guild?.roles.collection()
const data = col
?.array()
.map((c: Role, i: number) => {
return `${i + 1}. ${c.name}`
})
.join('\n') as string
msg.channel.send('Roles List:\n' + data)
} else if (msg.content === '!channels') {
const col = await msg.guild?.channels.array()
const data = col
?.map((c: GuildChannels, i: number) => {
return `${i + 1}. ${c.name}`
})
.join('\n') as string
msg.channel.send('Channels List:\n' + data)
} else if (msg.content === '!messages') {
const col = await msg.channel.messages.array()
const data = col
?.slice(-5)
.map((c: Message, i: number) => {
return `${i + 1}. ${c.content}`
})
.join('\n') as string
msg.channel.send('Top 5 Message List:\n' + data)
} else if (msg.content === '!editChannel') {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const channel = msg.channel as GuildTextChannel
const newChannel = await channel.edit({
name: 'gggg'
})
if (newChannel.name === 'gggg') {
msg.channel.send('Done!')
} else {
msg.channel.send('Failed...')
}
} else if (msg.content === '!react') {
msg.addReaction('a:programming:785013658257195008')
} else if (msg.content === '!wait_for') {
msg.channel.send('Send anything!')
const [receivedMsg] = await client.waitFor(
'messageCreate',
(message) => message.author.id === msg.author.id
)
msg.channel.send(`Received: ${receivedMsg?.content}`)
} else if (msg.content.startsWith('!collect') === true) {
let count = parseInt(msg.content.replace(/\D/g, ''))
if (isNaN(count)) count = 5
await msg.channel.send(`Collecting ${count} messages for 5s`)
const coll = new Collector({
event: 'messageCreate',
filter: (m) => m.author.id === msg.author.id,
deinitOnEnd: true,
max: count,
timeout: 5000
})
coll.init(client)
coll.collect()
coll.on('start', () => msg.channel.send('[COL] Started'))
coll.on('end', () =>
msg.channel.send(`[COL] Ended. Collected Size: ${coll.collected.size}`)
)
coll.on('collect', (msg) =>
msg.channel.send(`[COL] Collect: ${msg.content}`)
)
} else if (msg.content === '!attach') {
msg.channel.send({
file: await MessageAttachment.load(
'https://cdn.discordapp.com/emojis/626139395623354403.png?v=1'
)
})
} else if (msg.content === '!emattach') {
msg.channel.send(
new Embed()
.attach(
await MessageAttachment.load(
'https://cdn.discordapp.com/emojis/626139395623354403.png?v=1',
'file1.png'
),
await MessageAttachment.load(
'https://cdn.discordapp.com/emojis/626139395623354403.png?v=1',
'file2.png'
)
)
.setImage('attachment://file1.png')
.setThumbnail('attachment://file2.png')
)
} else if (msg.content === '!textfile') {
msg.channel.send({
files: [
new MessageAttachment('hello.txt', 'world'),
new MessageAttachment('world.txt', 'hello')
]
})
} else if (msg.content === '!join') {
if (msg.member === undefined) return
const vs = await msg.guild?.voiceStates.get(msg.member.id)
if (typeof vs !== 'object') return
vs.channel?.join()
} else if (msg.content === '!getOverwrites') {
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
if (!checkGuildTextBasedChannel(msg.channel)) {
return msg.channel.send("This isn't a guild text channel!")
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const overwrites = await (msg.channel as GuildTextChannel).overwritesFor(
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
msg.member as Member
)
msg.channel.send(
`Your permission overwrites:\n${overwrites
.map(
(over) =>
`ID: ${over.id}\nAllowed:\n${over.allow
.toArray()
.join('\n')}\nDenied:\n${over.deny.toArray().join('\n')}`
)
.join('\n\n')}`
)
} else if (msg.content === '!perms') {
if (msg.channel.type !== ChannelTypes.GUILD_TEXT) {
return msg.channel.send("This isn't a guild text channel!")
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const permissions = await ((msg.channel as unknown) as GuildTextChannel).permissionsFor(
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
msg.member as Member
)
msg.channel.send(`Your permissions:\n${permissions.toArray().join('\n')}`)
} else if (msg.content === '!addBasicOverwrites') {
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
if (!checkGuildTextBasedChannel(msg.channel)) {
return msg.channel.send("This isn't a guild text channel!")
}
if (msg.member !== undefined) {
await msg.channel.addOverwrite({
id: msg.member,
allow: Permissions.DEFAULT.toString()
})
msg.channel.send(`Done!`)
}
} else if (msg.content === '!updateBasicOverwrites') {
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
if (!checkGuildTextBasedChannel(msg.channel)) {
return msg.channel.send("This isn't a guild text channel!")
}
if (msg.member !== undefined) {
await msg.channel.editOverwrite(
{
id: msg.member,
allow: Permissions.DEFAULT.toString()
},
{
allow: OverrideType.REMOVE
}
)
msg.channel.send(`Done!`)
}
} else if (msg.content === '!addAllRoles') {
const roles = await msg.guild?.roles.array()
if (roles !== undefined) {
roles.forEach(async (role) => {
await msg.member?.roles.add(role)
console.log(role)
})
}
} else if (msg.content === '!createAndAddRole') {
if (msg.guild !== undefined) {
const role = await msg.guild.roles.create({
name: 'asdf',
permissions: 0
})
await msg.member?.roles.add(role)
}
} else if (msg.content === '!roles') {
let buf = 'Roles:'
if (msg.member === undefined) return
for await (const role of msg.member.roles) {
buf += `\n${role.name}`
}
msg.reply(buf)
} else if (msg.content === '!timer') {
msg.channel.send('3...').then((msg) => {
setTimeout(() => {
msg.edit('2...').then((msg) => {
setTimeout(() => {
msg.edit('1...').then((msg) => {
setTimeout(() => {
msg.edit('ok wut')
}, 1000)
})
}, 1000)
})
}, 1000)
})
}
})
client.on('messageReactionRemove', (reaction, user) => {
const msg = reaction.message
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
if (reaction.me && reaction.emoji.getEmojiString === '🤔') {
msg.removeReaction(reaction.emoji)
}
})
client.connect(TOKEN, Intents.None)
// OLD: Was a way to reproduce reconnect infinite loop
// setTimeout(() => {
// console.log('[DEBUG] Reconnect')
// client.gateway?.reconnect()
// }, 1000 * 4)

223
test/music.ts Normal file
View file

@ -0,0 +1,223 @@
import {
CommandClient,
event,
Intents,
command,
subslash,
groupslash,
CommandContext,
Extension,
Collection,
GuildTextChannel
} from '../../mod.ts'
import { LL_IP, LL_PASS, LL_PORT, TOKEN } from './config.ts'
import { Manager, Player } from 'https://deno.land/x/lavadeno/mod.ts'
import { Interaction } from '../structures/slash.ts'
import { slash } from '../client/mod.ts'
// import { SlashCommandOptionType } from '../types/slash.ts'
export const nodes = [
{
id: 'main',
host: LL_IP,
port: LL_PORT,
password: LL_PASS
}
]
class MyClient extends CommandClient {
manager: Manager
constructor() {
super({
prefix: ['.'],
caseSensitive: false
})
// eslint-disable-next-line @typescript-eslint/no-this-alias
const client = this
this.manager = new Manager(nodes, {
send(id, payload) {
// Sharding not added yet
client.gateway?.send(payload)
}
})
this.manager.on('socketError', ({ id }, error) =>
console.error(`${id} ran into an error`, error)
)
this.manager.on('socketReady', (node) =>
console.log(`${node.id} connected.`)
)
this.on('raw', (evt: string, d: any) => {
if (evt === 'VOICE_SERVER_UPDATE') this.manager.serverUpdate(d)
else if (evt === 'VOICE_STATE_UPDATE') this.manager.stateUpdate(d)
})
}
@subslash('cmd', 'sub-cmd-no-grp')
subCmdNoGroup(d: Interaction): void {
d.respond({ content: 'sub-cmd-no-group worked' })
}
@groupslash('cmd', 'sub-cmd-group', 'sub-cmd')
subCmdGroup(d: Interaction): void {
d.respond({ content: 'sub-cmd-group worked' })
}
@command()
rmrf(ctx: CommandContext): any {
if (ctx.author.id !== '422957901716652033') return
;((ctx.channel as any) as GuildTextChannel)
.bulkDelete(3)
.then((chan) => {
ctx.channel.send(`Bulk deleted 2 in ${chan}`)
})
.catch((e) => ctx.channel.send(`${e.message}`))
}
@slash()
run(d: Interaction): void {
console.log(d.name)
}
@event()
raw(evt: string, d: any): void {
if (!evt.startsWith('APPLICATION')) return
console.log(evt, d)
}
@event()
ready(): void {
console.log(`Logged in as ${this.user?.tag}!`)
this.manager.init(this.user?.id as string)
this.slash.commands.all().then(console.log)
// this.rest.api.users['422957901716652033'].get().then(console.log)
// client.slash.commands.create(
// {
// name: 'cmd',
// description: 'Parent command!',
// options: [
// {
// name: 'sub-cmd-group',
// type: SlashCommandOptionType.SUB_COMMAND_GROUP,
// description: 'Sub Cmd Group',
// options: [
// {
// name: 'sub-cmd',
// type: SlashCommandOptionType.SUB_COMMAND,
// description: 'Sub Cmd'
// }
// ]
// },
// {
// name: 'sub-cmd-no-grp',
// type: SlashCommandOptionType.SUB_COMMAND,
// description: 'Sub Cmd'
// },
// {
// name: 'sub-cmd-grp-2',
// type: SlashCommandOptionType.SUB_COMMAND_GROUP,
// description: 'Sub Cmd Group 2',
// options: [
// {
// name: 'sub-cmd-1',
// type: SlashCommandOptionType.SUB_COMMAND,
// description: 'Sub Cmd 1'
// },
// {
// name: 'sub-cmd-2',
// type: SlashCommandOptionType.SUB_COMMAND,
// description: 'Sub Cmd 2'
// }
// ]
// }
// ]
// },
// '783319033205751809'
// )
// client.slash.commands.delete('788719077329207296', '783319033205751809')
}
}
const players = new Collection<string, Player>()
class VCExtension extends Extension {
name = 'VC'
subPrefix = 'vc'
@command()
async join(ctx: CommandContext): Promise<any> {
if (players.has(ctx.guild?.id as string) === true)
return ctx.message.reply(`Already playing in this server!`)
ctx.argString = ctx.argString.slice(4).trim()
if (ctx.argString === '')
return ctx.message.reply('You gave nothing to search.')
const userVS = await ctx.guild?.voiceStates.get(ctx.author.id)
if (userVS === undefined) {
ctx.message.reply("You're not in VC.")
return
}
const player = (ctx.client as MyClient).manager.create(
ctx.guild?.id as string
)
await player.connect(userVS.channel?.id as string, { selfDeaf: true })
ctx.message.reply(`Joined VC channel - ${userVS.channel?.name}!`)
players.set(ctx.guild?.id as string, player)
ctx.channel.send(`Loading...`)
ctx.channel.send(`Searching for ${ctx.argString}...`)
const { track, info } = await player.manager
.search(`ytsearch:${ctx.argString}`)
.then((e) => e.tracks[0])
await player.play(track)
ctx.channel.send(`Now playing ${info.title}!\nDebug Track: ${track}`)
}
@command()
async leave(ctx: CommandContext): Promise<any> {
const userVS = await ctx.guild?.voiceStates.get(
(ctx.client.user?.id as unknown) as string
)
if (userVS === undefined) {
ctx.message.reply("I'm not in VC.")
return
}
userVS.channel?.leave()
ctx.message.reply(`Left VC channel - ${userVS.channel?.name}!`)
if (players.has(ctx.guild?.id as string) !== true)
return ctx.message.reply('Not playing anything in this server.')
const player = (players.get(ctx.guild?.id as string) as unknown) as Player
await player.stop()
await player.destroy()
players.delete(ctx.guild?.id as string)
ctx.message.reply('Stopped player')
}
}
const client = new MyClient()
client.on('raw', (e, d) => {
if (e === 'GUILD_MEMBER_ADD' || e === 'GUILD_MEMBER_UPDATE') console.log(e, d)
})
client.extensions.load(VCExtension)
client.connect(TOKEN, Intents.All)

27
test/slash-http.ts Normal file
View file

@ -0,0 +1,27 @@
import { SlashClient } from '../../mod.ts'
import { SLASH_ID, SLASH_PUB_KEY, SLASH_TOKEN } from './config.ts'
import { listenAndServe } from 'https://deno.land/std@0.90.0/http/server.ts'
const slash = new SlashClient({
id: SLASH_ID,
token: SLASH_TOKEN,
publicKey: SLASH_PUB_KEY
})
await slash.commands.bulkEdit([
{
name: 'ping',
description: 'Just ping!'
}
])
const options = { port: 8000 }
console.log('Listen on port: ' + options.port.toString())
listenAndServe(options, async (req) => {
const d = await slash.verifyServerRequest(req)
if (d === false) return req.respond({ status: 401, body: 'not authorized' })
console.log(d)
if (d.type === 1) return d.respond({ type: 1 })
d.reply('Pong!')
})

18
test/slash-only.ts Normal file
View file

@ -0,0 +1,18 @@
import { SlashClient } from '../models/slashClient.ts'
import { SlashCommandPartial } from '../types/slash.ts'
import { TOKEN } from './config.ts'
export const slash = new SlashClient({ token: TOKEN })
console.log(slash.modules)
// Cmd objects come here
const commands: SlashCommandPartial[] = []
console.log('Creating...')
commands.forEach((cmd) => {
slash.commands
.create(cmd, '!! Your testing guild ID comes here !!')
.then((c) => console.log(`Created command ${c.name}!`))
.catch((e) => `Failed to create ${cmd.name} - ${e.message}`)
})

64
test/slash.ts Normal file
View file

@ -0,0 +1,64 @@
import {
Client,
Intents,
event,
slash,
SlashCommandOptionType as Type
} from '../../mod.ts'
import { Interaction } from '../structures/slash.ts'
import { TOKEN } from './config.ts'
export class MyClient extends Client {
@event() ready(): void {
console.log(`Logged in as ${this.user?.tag}!`)
this.slash.commands.bulkEdit(
[
{
name: 'test',
description: 'Test command.',
options: [
{
name: 'user',
type: Type.USER,
description: 'User'
},
{
name: 'role',
type: Type.ROLE,
description: 'Role'
},
{
name: 'channel',
type: Type.CHANNEL,
description: 'Channel'
},
{
name: 'string',
type: Type.STRING,
description: 'String'
}
]
}
],
'807935370556866560'
)
this.slash.commands.bulkEdit([])
}
@slash() test(d: Interaction): void {
console.log(d.resolved)
}
@event() raw(evt: string, d: any): void {
if (evt === 'INTERACTION_CREATE') console.log(evt, d?.data?.resolved)
}
}
const client = new MyClient({
presence: {
status: 'dnd',
activity: { name: 'Slash Commands', type: 'LISTENING' }
}
})
client.connect(TOKEN, Intents.None)

21
test/template.ts Normal file
View file

@ -0,0 +1,21 @@
import { Client, Intents } from '../../mod.ts'
import { TOKEN } from './config.ts'
const client = new Client()
client.on('guildLoaded', async (guild) => {
if (guild.id === 'GUILD_ID') {
console.log((await guild.syncTemplate('TEMPLATE_ID')).code)
console.log(
(
await guild.editTemplate('TEMPLATE_ID', {
name: 'asdf',
description: 'asdfasdfasdf'
})
).code
)
console.log((await guild.deleteTemplate('TEMPLATE_ID')).id)
}
})
client.connect(TOKEN, Intents.All)

14
test/user.ts Normal file
View file

@ -0,0 +1,14 @@
import { Client, Intents } from '../mod.ts'
import { TOKEN } from './config.ts'
const client = new Client()
client.on('ready', async () => {
client.editUser({
username: 'Learning'
})
const channel = await client.createDM('USER_ID')
channel.send('nice')
})
client.connect(TOKEN, Intents.All)