当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript js.Client.on方法代码示例

本文整理汇总了TypeScript中discord.js.Client.on方法的典型用法代码示例。如果您正苦于以下问题:TypeScript js.Client.on方法的具体用法?TypeScript js.Client.on怎么用?TypeScript js.Client.on使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在discord.js.Client的用法示例。


在下文中一共展示了js.Client.on方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: getClient

 public async getClient(userId: string | null = null): Promise<DiscordClient> {
     if (userId === null) {
         return this.botClient;
     }
     if (this.clients.has(userId)) {
         log.verbose("Returning cached user client for", userId);
         return this.clients.get(userId) as DiscordClient;
     }
     const discordIds = await this.store.get_user_discord_ids(userId);
     if (discordIds.length === 0) {
         return Promise.resolve(this.botClient);
     }
     // TODO: Select a profile based on preference, not the first one.
     const token = await this.store.get_token(discordIds[0]);
     const client = new DiscordClient({
         fetchAllMembers: true,
         messageCacheLifetime: 5,
         sync: true,
     });
     const jsLog = new Log("discord.js-ppt");
     client.on("debug", (msg) => { jsLog.verbose(msg); });
     client.on("error", (msg) => { jsLog.error(msg); });
     client.on("warn", (msg) => { jsLog.warn(msg); });
     try {
         await client.login(token);
         log.verbose("Logged in. Storing ", userId);
         this.clients.set(userId, client);
         return client;
     } catch (err) {
         log.warn(`Could not log ${userId} in. Returning bot user for now.`, err);
         return this.botClient;
     }
 }
开发者ID:Half-Shot,项目名称:matrix-appservice-discord,代码行数:33,代码来源:clientfactory.ts

示例2: start

    public start(): void{
        // start the bot
        this.client.on("ready", () => {
            // initialize the guild objects for the bot instance
            this.initGuilds();


            
            // set the 'playing' status
            this.client.user.setPresence({game: {name: this.presence, type: 0}});

            
            // print startup time
            console.log("Bot started @ " + this.getTime());
        
        });

        // message in view
        this.client.on("message", (msg) => {
            // get description
            if(msg.content.startsWith(this.prefix + "desc")){
                let command = msg.content.substr(1).split(" ").slice(1);
                let response = this.commandHandler.getDescription(command);
                if(response != undefined) { msg.channel.send(response); }
            // get command
            } else if(msg.content.startsWith(this.prefix)){
                let command = msg.content.substr(1).split(" ");
                let args = command.slice(1);
                args.db = this.database;
                
                // find the guild object where the ID matches.
                let guild = this.guilds.find(g => g.id == msg.guild.id);
                if(guild != undefined && guild.checkCooldown(command, 1000)){
                    let response = this.commandHandler.execCommand(command[0], args);
                    // make sure response is valid.
                    if(response != undefined) { msg.channel.send(response); }
                }
            }
        });

        // join new guild
        this.client.on("guildCreate", (guild) => {
            this.database.addGuild(guild);
        });

        // removed from guild
        this.client.on("guildDelete", (guild) => {
            this.database.deleteGuild(guild);
        });

        
    }
开发者ID:Avuxo,项目名称:senjou,代码行数:52,代码来源:senjou.ts

示例3: createConnection

createConnection(connectionOptions).then(conn => {
    try {
    console.log("Typeorm connected to database.");

    var bot = new Discord.Client();

    bot.on('ready', () => readyEvent(bot));
    bot.on('presenceUpdate', presenceEvent);
    bot.on('message', messageEvent(bot));

    bot.login(Configuration.DISCORD_TOKEN);
    } catch (ex) {
        console.error(ex);
    }
}).catch(err => {
开发者ID:Goyatuzo,项目名称:LurkerBot,代码行数:15,代码来源:app.ts

示例4: async

 return new Bluebird<string>((resolve, reject) => {
     client.on("ready", async () => {
         const id = client.user.id;
         await client.destroy();
         resolve(id);
     });
     client.login(token).catch(reject);
 }).timeout(READY_TIMEOUT).catch((err: Error) => {
开发者ID:Half-Shot,项目名称:matrix-appservice-discord,代码行数:8,代码来源:clientfactory.ts

示例5: registerEvents

function registerEvents() {
    client.on('message', message => {
        const author = message.author;

        // Log public messages
        if (message.channel instanceof Discord.TextChannel) {
            messageSaver.messagesPosted(message);
        } else if (message.channel instanceof Discord.PMChannel) {
            loggy.log(`${Emoji.MESSAGE} Message from ` +
                `${author} ${Emoji.MORE}`, message.cleanContent);
        }
        // Receive our pending messages
        if (author === client.user) {
            messager.receiveOwnMessage(message);
            return;
        }
        // Respond to commands
        takeCommand(message).catch(error => {
            loggy.error(`Couldn't take ${author.name}'s ` +
                `command "${message.cleanContent}" ` +
                `${Emoji.MORE}`, error)
        });
    });
    client.on('messageUpdated', (oldMessage, newMessage) => {
        messageSaver.messageUpdated(oldMessage, newMessage);
    });
    client.on('messageDeleted', message => {
        messageSaver.messageDeleted(message);
    });

    client.on('serverCreated', server => {
        if (timelines.has(server)) {
            loggy.error(`Oh no, ${server.name} is already timelined`);
        } else timelines.set(server, createServerTimeline(server));

        root.child(`timelines/as_of/${server.id}`).once('value')
        .then(serverSnap => messager.type(server, !serverSnap.exists() ? [
            `Hi I'm ${client.user.name}, and someone sent me here`,
            `I make live dot plots of your server's activity stats so you can always see which channels are **poppin**.`,
            `Here's the graph for ${server.name}: ${getLiveUrl(server.id)}`
        ] : [
            `Hi I'm ${client.user.name} and someone has brought me back`,
            `Once again, my live dot plot of ${server.name} is at ${getLiveUrl(server.id)}`
        ]));
    });
    client.on('serverDeleted', server => {
        loggy.log(`${Emoji.LEAVE} Just left ${server.name}`);
        timelines.get(server).destroy();
        timelines.delete(server);
    });

    /*client.on('userBanned', (user, server) => {
        if (user !== client.user) return;
        loggy.error(`Daaang I just got banned from ${server.name}!`);
    });
    client.on('userTypingStarted', (user, channel:Discord.TextChannel) => {
        if (!channel.server) return; // A PM channel
        //loggy.log(`Ho boy ${channel.name} get ready for a brand spanking steamy new post from ${user.name}`);
    });
    client.on('userTypingStopped', (user, channel:Discord.TextChannel) => {
        if (!channel.server) return; // A PM channel
        //loggy.log(`Aww ${channel.name} just saw ${user.name} stop typing`);
    });*/

    client.on('serverUpdated', (old, server) => {
        timelines.get(server).update(objectifyServer(server));
    });
    client.on('channelCreated', (channel:Discord.ServerChannel) => {
        if (channel.server) timelines.get(channel.server).update(
            objectifyChannel(channel));
    });
    client.on('channelUpdated', (old, channel:Discord.ServerChannel) => {
        if (channel.server) timelines.get(channel.server).update(
            objectifyChannel(channel));
    });
    client.on('channelDeleted', (channel:Discord.ServerChannel) => {
        if (!channel.server) return;
        const update = deletify(objectifyChannel(channel));

        if (channel.type === 'voice') { // Bad news for these guys
            const voice = channel as Discord.VoiceChannel;
            Object.assign(update, ...voice.members.map(
                member => objectifyMember(channel.server, member)));
        }
        timelines.get(channel.server).update(update);
    });

    client.on('serverNewMember', (server, user) => {
        timelines.get(server).update(
            objectifyMember(server, user));
    });
    client.on('serverMemberUpdated', (server, user, userOld) => {
        timelines.get(server).update(
            objectifyMember(server, user));
    });
    client.on('serverMemberRemoved', (server, user) => {
        timelines.get(server).update(
            deletify(objectifyMember(server, user)));
    });

//.........这里部分代码省略.........
开发者ID:fernozzle,项目名称:poppin-bot,代码行数:101,代码来源:server.ts

示例6: objectifyMember

        for (const server of servers) {
            timelines.get(server).update(
                objectifyMember(server, user));
        }
    });
    client.on('disconnected', () => {
        login();
    });
}

client.on('ready', () => {

    client.userAgent.url     = module.exports.homepage;
    client.userAgent.version = module.exports.version;
    client.setPlayingGame(config.get('settings.discordStatus') + '');

    console.dir(client.servers.map(s => s.name));
    const logServer = client.servers.get(config.get('settings.logServer'));
    if (logServer) init(logServer);
    else console.error('Not admitted to log server');
});


function channelsInfo(servers) {
    const channelLine = (channel, i, tcs) =>
        ((i === tcs.length - 1) ? '\u2517' : '\u2523') +
        ` ${Emoji.CHANNEL} ${channel.name}`;
    const channelList = server =>
        server.channels.getAll('type', 'text')
            .map(channelLine).join('\n');
    return servers.map(server =>
开发者ID:fernozzle,项目名称:poppin-bot,代码行数:31,代码来源:server.ts

示例7: Client

  ------------ IMPORTS, INSTANCES, AND VARIABLES ------------
*/
import { Client, Message, TextChannel, MessageReaction, User, Channel, GuildMember } from "discord.js" // Import needed classes from discord.js library
import { joinChannel, leaveChannel, doRoles, prune, authenticate, rawReactionEmitter } from "./handlers" // import methods from my handler library
import config from "../config"
// Instantiate a client to use it
const client: Client = new Client()
/*
  ------------ LISTENERS ------------
*/
/**
 * Spit out unhandled errors without panicking
 * @listens error
 * @todo Replace it to handle specific error events as they arise
 */
client.on(`error`, (error: ErrorEvent) => console.error(`ERROR: ${error.message}`))
/**
 * Parse commands and fires the appropriate handler
 * @listens message
 */
client.on(`message`, (message: Message) => {
  // Check if message is a command
  if(message.content.startsWith(config.prefix)) {
    // Splits message into command and arguments
    var text: string[] = message.content.toLowerCase().split(` `)
    var command: string = text[0].substr(1)
    text.shift()
    // Matches command with known commands
    switch(command) {
      /*
        If it's a public command, it fires the handler straight away
开发者ID:Zunon,项目名称:Sagiri,代码行数:31,代码来源:main.ts

示例8: Client

/// <reference path='index.d.ts' />

import { Collector, Message, CollectorFilter, Client, CollectorHandler, MessageReaction, Collection, User, ReactionCollectorOptions, Snowflake } from 'discord.js';

const client = new Client({
	disableEveryone: false,
	disabledEvents: ['GUILD_MEMBER_ADD']
});

client.on('message', (message) => {
	if (message.content === 'hello') {
		message.channel.sendMessage('o/');
	}

	const collector: ReactionCollector = new ReactionCollector(message,
		(reaction: MessageReaction) => reaction.emoji.toString() === '👌',
		{ time: 30e3 });
	collector.on('end', collected => console.log(collected));
});

client.login('dsfsd754.4fds4f68d4f6sd46f4s.7878easfdsgdfFDSIJIO');

export class TestCollector extends Collector<Snowflake, Message> {
	public filter: CollectorFilter;
	public constructor(client: Client, filter: CollectorFilter, ) {
		super(client, filter);
	}

	public handle(message: Message): CollectorHandler<Snowflake, Message> {
		return { key: message.id, value: message };
	}
开发者ID:Mstrodl,项目名称:mstrodl.github.io,代码行数:31,代码来源:discord.js-test.ts

示例9: resolve

 return new Bluebird<void>((resolve, reject) => {
     this.botClient.on("ready", () => {
         resolve();
     });
     this.botClient.login(this.config.botToken).catch(reject);
 }).timeout(READY_TIMEOUT).catch((err) => {
开发者ID:Half-Shot,项目名称:matrix-appservice-discord,代码行数:6,代码来源:clientfactory.ts

示例10: Client

/// <reference path='index.d.ts' />

import { Client } from 'discord.js';

const client = new Client({
	disableEveryone: false
});

client.on('message', (message) => {
	if (message.content === 'hello') {
		message.channel.sendMessage('o/');
	}
});

client.login('dsfsd754.4fds4f68d4f6sd46f4s.7878easfdsgdfFDSIJIO');
开发者ID:afrosamasenpai,项目名称:samples,代码行数:15,代码来源:discord.js-test.ts


注:本文中的discord.js.Client.on方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。