Skip to content

Commit

Permalink
remove people, fix wallet issues
Browse files Browse the repository at this point in the history
  • Loading branch information
lalalune committed Nov 29, 2024
2 parents 62e7417 + c04310f commit 4ad11c4
Show file tree
Hide file tree
Showing 10 changed files with 177 additions and 87 deletions.
12 changes: 6 additions & 6 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -85,16 +85,16 @@ LARGE_HEURIST_LANGUAGE_MODEL=
HEURIST_IMAGE_MODEL=

# EVM
EVM_PRIVATE_KEY=EXAMPLE_WALLET_PRIVATE_KEY
EVM_PUBLIC_KEY=EXAMPLE_WALLET_PUBLIC_KEY
EVM_PRIVATE_KEY=
EVM_PUBLIC_KEY=

# Solana
SOLANA_PRIVATE_KEY=EXAMPLE_WALLET_PRIVATE_KEY
SOLANA_PUBLIC_KEY=EXAMPLE_WALLET_PUBLIC_KEY
SOLANA_PRIVATE_KEY=
SOLANA_PUBLIC_KEY=

# Fallback Wallet Configuration (deprecated)
WALLET_PRIVATE_KEY=EXAMPLE_WALLET_PRIVATE_KEY
WALLET_PUBLIC_KEY=EXAMPLE_WALLET_PUBLIC_KEY
WALLET_PRIVATE_KEY=
WALLET_PUBLIC_KEY=

BIRDEYE_API_KEY=

Expand Down
12 changes: 10 additions & 2 deletions agent/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,10 @@ export function parseArguments(): {
character?: string;
characters?: string;
} {
console.log("parsing arguments")
console.log("process.argv", process.argv)
try {
return yargs(process.argv.slice(2))
return yargs(process.argv.slice(3))
.option("character", {
type: "string",
description: "Path to the character JSON file",
Expand Down Expand Up @@ -88,8 +90,10 @@ export async function loadCharacters(
?.split(",")
.map((filePath) => filePath.trim());
const loadedCharacters = [];
console.log("****characterPaths", characterPaths)

if (characterPaths?.length > 0) {
console.log("has characters")
for (const characterPath of characterPaths) {
let content = null;
let resolvedPath = "";
Expand All @@ -115,6 +119,7 @@ export async function loadCharacters(
content = tryLoadFile(tryPath);
if (content !== null) {
resolvedPath = tryPath;
console.log("resolvedPath", resolvedPath)
break;
}
}
Expand All @@ -131,6 +136,7 @@ export async function loadCharacters(
try {
const character = JSON.parse(content);
validateCharacterConfig(character);
console.log("character is", character)

// Handle plugins
if (character.plugins) {
Expand Down Expand Up @@ -371,7 +377,8 @@ async function startAgent(character: Character, directClient) {
fs.mkdirSync(dataDir, { recursive: true });
}

db = initializeDatabase(dataDir);
db = initializeDatabase(dataDir) as IDatabaseAdapter &
IDatabaseCacheAdapter;

await db.init();

Expand Down Expand Up @@ -403,6 +410,7 @@ const startAgents = async () => {
const args = parseArguments();

let charactersArg = args.characters || args.character;
console.log("charactersArg is", charactersArg)

let characters = [defaultCharacter];

Expand Down
1 change: 0 additions & 1 deletion characters/eternalai.character.json
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,6 @@
"vaguely offensive but also hilarious",
"schizo-autist"
],
"people": [],
"topics": [
"metaphysics",
"quantum physics",
Expand Down
1 change: 0 additions & 1 deletion characters/tate.character.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
"model": "en_US-male-medium"
}
},
"people": [],
"plugins": [],
"bio": [
"Andrew Tate is a former kickboxer, entrepreneur, and self-proclaimed misogynist.",
Expand Down
1 change: 0 additions & 1 deletion characters/trump.character.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
"model": "en_US-male-medium"
}
},
"people": ["Kamala Harris", "Joe Biden", "Sleepy Joe"],
"plugins": [],
"bio": [
"SAVED America from the China Virus (while they let cities burn)",
Expand Down
227 changes: 156 additions & 71 deletions packages/client-discord/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { MessageManager } from "./messages.ts";
import channelStateProvider from "./providers/channelState.ts";
import voiceStateProvider from "./providers/voiceState.ts";
import { VoiceManager } from "./voice.ts";
import { validateDiscordConfig } from "./enviroment.ts";
import { PermissionsBitField } from "discord.js";

export class DiscordClient extends EventEmitter {
apiToken: string;
Expand All @@ -34,6 +34,7 @@ export class DiscordClient extends EventEmitter {

constructor(runtime: IAgentRuntime) {
super();

this.apiToken = runtime.getSetting("DISCORD_API_TOKEN") as string;
this.client = new Client({
intents: [
Expand Down Expand Up @@ -112,85 +113,173 @@ export class DiscordClient extends EventEmitter {

private async onClientReady(readyClient: { user: { tag: any; id: any } }) {
elizaLogger.success(`Logged in as ${readyClient.user?.tag}`);

// Register slash commands
const commands = [
{
name: "joinchannel",
description: "Join a voice channel",
options: [
{
name: "channel",
type: 7, // CHANNEL type
description: "The voice channel to join",
required: true,
channel_types: [2], // GuildVoice type
},
],
},
{
name: "leavechannel",
description: "Leave the current voice channel",
},
];

try {
await this.client.application?.commands.set(commands);
elizaLogger.success("Slash commands registered");
} catch (error) {
console.error("Error registering slash commands:", error);
}

// Required permissions for the bot
const requiredPermissions = [
// Text Permissions
PermissionsBitField.Flags.ViewChannel,
PermissionsBitField.Flags.SendMessages,
PermissionsBitField.Flags.SendMessagesInThreads,
PermissionsBitField.Flags.CreatePrivateThreads,
PermissionsBitField.Flags.CreatePublicThreads,
PermissionsBitField.Flags.EmbedLinks,
PermissionsBitField.Flags.AttachFiles,
PermissionsBitField.Flags.AddReactions,
PermissionsBitField.Flags.UseExternalEmojis,
PermissionsBitField.Flags.UseExternalStickers,
PermissionsBitField.Flags.MentionEveryone,
PermissionsBitField.Flags.ManageMessages,
PermissionsBitField.Flags.ReadMessageHistory,
// Voice Permissions
PermissionsBitField.Flags.Connect,
PermissionsBitField.Flags.Speak,
PermissionsBitField.Flags.UseVAD,
PermissionsBitField.Flags.PrioritySpeaker,
].reduce((a, b) => a | b, 0n);

elizaLogger.success("Use this URL to add the bot to your server:");
elizaLogger.success(
`https://discord.com/api/oauth2/authorize?client_id=${readyClient.user?.id}&permissions=0&scope=bot%20applications.commands`
`https://discord.com/api/oauth2/authorize?client_id=${readyClient.user?.id}&permissions=${requiredPermissions}&scope=bot%20applications.commands`
);
await this.onReady();
}

async handleReactionAdd(reaction: MessageReaction, user: User) {
elizaLogger.log("Reaction added");
// if (user.bot) return;

let emoji = reaction.emoji.name;
if (!emoji && reaction.emoji.id) {
emoji = `<:${reaction.emoji.name}:${reaction.emoji.id}>`;
}
try {
elizaLogger.log("Reaction added");

// Fetch the full message if it's a partial
if (reaction.partial) {
try {
await reaction.fetch();
} catch (error) {
console.error(
"Something went wrong when fetching the message:",
error
);
// Early returns
if (!reaction || !user) {
elizaLogger.warn("Invalid reaction or user");
return;
}
}

const messageContent = reaction.message.content;
const truncatedContent =
messageContent.length > 100
? messageContent.substring(0, 100) + "..."
: messageContent;
// Get emoji info
let emoji = reaction.emoji.name;
if (!emoji && reaction.emoji.id) {
emoji = `<:${reaction.emoji.name}:${reaction.emoji.id}>`;
}

const reactionMessage = `*<${emoji}>: "${truncatedContent}"*`;
// Fetch full message if partial
if (reaction.partial) {
try {
await reaction.fetch();
} catch (error) {
elizaLogger.error(
"Failed to fetch partial reaction:",
error
);
return;
}
}

const roomId = stringToUuid(
reaction.message.channel.id + "-" + this.runtime.agentId
);
const userIdUUID = stringToUuid(user.id + "-" + this.runtime.agentId);
// Generate IDs with timestamp to ensure uniqueness
const timestamp = Date.now();
const roomId = stringToUuid(
`${reaction.message.channel.id}-${this.runtime.agentId}`
);
const userIdUUID = stringToUuid(
`${user.id}-${this.runtime.agentId}`
);
const reactionUUID = stringToUuid(
`${reaction.message.id}-${user.id}-${emoji}-${timestamp}-${this.runtime.agentId}`
);

// Validate IDs
if (!userIdUUID || !roomId) {
elizaLogger.error("Invalid user ID or room ID", {
userIdUUID,
roomId,
});
return;
}

// Generate a unique UUID for the reaction
const reactionUUID = stringToUuid(
`${reaction.message.id}-${user.id}-${emoji}-${this.runtime.agentId}`
);
// Process message content
const messageContent = reaction.message.content || "";
const truncatedContent =
messageContent.length > 100
? `${messageContent.substring(0, 100)}...`
: messageContent;
const reactionMessage = `*<${emoji}>: "${truncatedContent}"*`;

// Get user info
const userName = reaction.message.author?.username || "unknown";
const name = reaction.message.author?.displayName || userName;

// Ensure connection
await this.runtime.ensureConnection(
userIdUUID,
roomId,
userName,
name,
"discord"
);

// Create memory with retry logic
const memory = {
id: reactionUUID,
userId: userIdUUID,
agentId: this.runtime.agentId,
content: {
text: reactionMessage,
source: "discord",
inReplyTo: stringToUuid(
`${reaction.message.id}-${this.runtime.agentId}`
),
},
roomId,
createdAt: timestamp,
embedding: getEmbeddingZeroVector(this.runtime),
};

// ensure the user id and room id are valid
if (!userIdUUID || !roomId) {
console.error("Invalid user id or room id");
return;
try {
await this.runtime.messageManager.createMemory(memory);
elizaLogger.debug("Reaction memory created", {
reactionId: reactionUUID,
emoji,
userId: user.id,
});
} catch (error) {
if (error.code === "23505") {
// Duplicate key error
elizaLogger.warn("Duplicate reaction memory, skipping", {
reactionId: reactionUUID,
});
return;
}
throw error; // Re-throw other errors
}
} catch (error) {
elizaLogger.error("Error handling reaction:", error);
}
const userName = reaction.message.author.username;
const name = reaction.message.author.displayName;

await this.runtime.ensureConnection(
userIdUUID,
roomId,
userName,
name,
"discord"
);

// Save the reaction as a message
await this.runtime.messageManager.createMemory({
id: reactionUUID, // This is the ID of the reaction message
userId: userIdUUID,
agentId: this.runtime.agentId,
content: {
text: reactionMessage,
source: "discord",
inReplyTo: stringToUuid(
reaction.message.id + "-" + this.runtime.agentId
), // This is the ID of the original message
},
roomId,
createdAt: Date.now(),
embedding: getEmbeddingZeroVector(this.runtime),
});
}

async handleReactionRemove(reaction: MessageReaction, user: User) {
Expand Down Expand Up @@ -298,12 +387,8 @@ export function startDiscord(runtime: IAgentRuntime) {
}

export const DiscordClientInterface: ElizaClient = {
start: async (runtime: IAgentRuntime) => {
await validateDiscordConfig(runtime);

return new DiscordClient(runtime);
},
stop: async (_runtime: IAgentRuntime) => {
start: async (runtime: IAgentRuntime) => new DiscordClient(runtime),
stop: async (runtime: IAgentRuntime) => {

Check failure on line 391 in packages/client-discord/src/index.ts

View workflow job for this annotation

GitHub Actions / check

'runtime' is defined but never used. Allowed unused args must match /^_/u
console.warn("Discord client does not support stopping yet");
},
};
};
1 change: 0 additions & 1 deletion packages/core/src/defaultCharacter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,6 @@ export const defaultCharacter: Character = {
"vaguely offensive but also hilarious",
"schizo-autist",
],
people: [],
topics: [
// broad topics
"metaphysics",
Expand Down
1 change: 0 additions & 1 deletion packages/core/src/enviroment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ export const CharacterSchema = z.object({
lore: z.array(z.string()),
messageExamples: z.array(z.array(MessageExampleSchema)),
postExamples: z.array(z.string()),
people: z.array(z.string()),
topics: z.array(z.string()),
adjectives: z.array(z.string()),
knowledge: z.array(z.string()).optional(),
Expand Down
Loading

0 comments on commit 4ad11c4

Please sign in to comment.