CryptoとAIエージェントの力でDiscordを盛り上げましょう!
こんばんは、Komlock labのWeb3エンジニア、ズルです!
Discordコミュニティ(特に暗号通貨関連)があまり活発でないと感じていませんか?メンバーのエンゲージメントを高めるのは大変に思えるかもしれません。しかし実は、AIエージェントを活用して、最もアクティブなメンバーを自動的に検知・報酬を与える方法があります。
AIエージェントでエンゲージメントを高める方法
DiscordサーバーにAIエージェントを導入することで、
- メッセージのやり取りを容易にモニタリング
- アクティブなユーザーにトークンを自動的に配布
といった仕組みを実現できます。
特に暗号通貨トークンを使った報酬は、メンバーの参加やアイデアを認める形にもなり、適度な競争心を刺激するので、サーバーをより活性化させられます。
本記事では、Coinbase Developer Platform SDKを使った例を紹介します。
- 前日のチャット履歴を取得
Botが指定したチャンネルから特定の期間内のメッセージをすべて取得します。 - AIエージェントにデータを渡す
AIモデルがチャット履歴を分析し、各ユーザーの貢献度を評価します。 - 最も貢献度の高いユーザーに報酬を付与
Discordボットのセットアップ
- Discordライブラリーをインストール
pip install discord
- Discordに接続する
import discord
from discord.ext import commands
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
DISCORD_BOT_TOKEN = "INSERT_DISCORD_BOT_TOKEN_HERE"
@bot.event
async def on_ready():
print(f"Logged in discord as {bot.user.name}")
await bot.close()
bot.run(DISCORD_BOT_TOKEN)
AIが最もインパクトのあったユーザーのウォレットアドレスに、トークンを送金します。
上記のコードは、Discordに接続してBotを起動するための最も基本的な例です。Discorボットのトークンは、Discord Developer Portalでアプリケーションを作成し、Botを設定して取得できます。
また、「Privileged Gateway Intents」(特に「Message Content Intent」)を有効にする必要があります。これを有効にしないと、Discordのメッセージ履歴を取得できません。
より詳しいBotのセットアップ手順は、このチュートリアルも参照してください。
前日のチャット履歴を取得する
async def fetch_messages(start_time, end_time):
CHANNEL_NAME = "general"
result = ""
for guild in bot.guilds:
for channel in guild.text_channels:
if channel.name == CHANNEL_NAME:
result += f'Channel :{channel.name} ({start_time.date()} ~ {end_time.date()})--------------\n'
try:
async for msg in channel.history(limit=None, after=start_time, before=end_time, oldest_first=True):
if msg.author.bot:
continue # Skip bot messages
user_wallet = USER_WALLETS_ADDRESS.get(msg.author.name) or "0x0000000000000000000000000000000000000000"
text = f"{msg.author.name}({user_wallet}) : {msg.content}\n"
result += text
except Exception as e:
print(f"Could not read channel {channel.name}: {e}")
result += "--------------------------------------------------------\n"
return result
取得された結果の例:
Channel :general (2025-01-10 ~ 2025-01-11)--------------
userA (0x123456789BdE4723f80A7C15f8F9d9AeEc15E221): Hey everyone, any tips for beating the boss in level 5?
userB (0x8C14F78DeF81bC2457D123456789AC4C92E89A12): Try using the Frost Blade; it slows the boss down.
userC (0x1A67B4dEc8bF3d21Af9C8f4b123456789d89Fa12): Wow, I didn't know that! Thanks for the tip!
userA (0x123456789BdE4723f80A7C15f8F9d9AeEc15E221): I'll try that, but where do I find the Frost Blade?
userB (0x8C14F78DeF81bC2457D123456789AC4C92E89A12): Check the Ice Caverns. It's in the hidden chest near the northern wall.
userC (0x1A67B4dEc8bF3d21Af9C8f4b123456789d89Fa12): Just joined this server; what's this bot about?
userA (0x123456789BdE4723f80A7C15f8F9d9AeEc15E221): It's an AI that rewards helpful contributions! If you're active and share good tips, you can earn tokens.
userD (0x9Ef3A8D42Bc1E17D3f64A7E24Ce89Df124526634): That sounds awesome!
userB (0x8C14F78DeF81bC2457D123456789AC4C92E89A12): By the way, if you're farming tokens, the Desert Shrine is the best spot!
userA (0x123456789BdE4723f80A7C15f8F9d9AeEc15E221): Thanks for the advice; I'll head there next!
--------------------------------------------------------
報酬付与のルール
"""
You are an AI Agent for a blockchain-based gaming community where players share strategies, debug issues, and collaborate on battle tactics. The channel is the community's go-to space for active discussions and helping new members. Every day, the most impactful contributor in the channel is rewarded with 0.1 USDC to encourage meaningful engagement. It is possible to have no winner if no user meets the criteria.
Impactful User Definitions:
• Shares helpful game strategies or technical solutions.
• Actively engages with other players by answering questions or sparking discussions.
• Welcomes and assists new players by explaining the game or community features.
• Contributions must be meaningful, engaging, and not spammy.
Task:
Analyze the channel history provided below, identify the most impactful user, and transfer to them 0.1 USDC.
"""
• このように、コミュニティやDiscordチャンネルの文脈を説明し、どのような貢献が「最もインパクトのある貢献」と見なされるかを定義します。
• AIエージェントはこれらのガイドラインをもとに、前日のチャット履歴から受賞者を選びます。
注: Coinbase Developer Platform SDKでは、ETHとUSDCのみがサポートされているため、ここではUSDCを報酬として使います。Base Sepoliaネットワークであれば、エージェントが自動的にBase faucetからUSDCを取得できますが、手動でウォレットに資金を送ることも可能です。
AIエージェントの実行結果
-------------------
The most impactful user identified from the channel history is **userB** (0x8C14F78DeF81bC2457D123456789AC4C92E89A12) for providing helpful tips and engaging with other users.
I have successfully transferred **0.1 USDC** to userB. You can view the transaction details [here](https://sepolia.basescan.org/tx/0xd7c1434760b0ab752caece0bda).
-------------------
完了です!
コミュニティをこんなに手軽に盛り上げられるなんて、想像したことなかったですね。AIエージェントを活用して参加状況をモニタリングし、トークンを配布することで、適度な競争心とコミュニティ全体の成長を促すことができます。プロジェクトのオーナーでも教育者でもインフルエンサーでも、コミュニティへの報酬施策は大きなメリットをもたらすでしょう。活発な議論を巻き起こし、知識を共有し、メンバーを繋ぎ続ける――ぜひ一度お試しください。きっとあなたの暗号通貨コミュニティはさらに活気づくはずです!
フルソースコード
import discord
from discord.ext import commands
from datetime import datetime, timedelta, timezone
import os
from langchain_core.messages import HumanMessage
from langchain_openai import ChatOpenAI
from langgraph.checkpoint.memory import MemorySaver
from langgraph.prebuilt import create_react_agent
# Import CDP Agentkit Langchain Extension.
from cdp_langchain.agent_toolkits import CdpToolkit
from cdp_langchain.utils import CdpAgentkitWrapper
# Configure a file to persist the agent's CDP MPC Wallet Data.
wallet_data_file = "wallet_data.txt"
DISCORD_BOT_TOKEN = "INSERT_DISCORD_BOT_TOKEN_HERE"
USER_WALLETS_ADDRESS = {
"userA": "0x123456789BdE4723f80A7C15f8F9d9AeEc15E221",
"userB": "0x8C14F78DeF81bC2457D123456789AC4C92E89A12",
"userC": "0x1A67B4dEc8bF3d21Af9C8f4b123456789d89Fa12",
"userD": "0x9Ef3A8D42Bc1E17D3f64A7E24Ce89Df124526634",
}
PROMPT_BEGINNING_TEXT = """
You are an AI Agent for a blockchain-based gaming community where players share strategies, debug issues, and collaborate on battle tactics. The channel is the community's go-to space for active discussions and helping new members. Every day, the most impactful contributor in the channel is rewarded with 0.1 USDC to encourage meaningful engagement. It is possible to have no winner if no user meets the criteria.
Impactful User Definitions:
• Shares helpful game strategies or technical solutions.
• Actively engages with other players by answering questions or sparking discussions.
• Welcomes and assists new players by explaining the game or community features.
• Contributions must be meaningful, engaging, and not spammy.
Task:
Analyze the channel history provided below, identify the most impactful user, and transfer to them 0.1 USDC.
"""
def initialize_agent():
"""Initialize the agent with CDP Agentkit."""
# Initialize LLM.
llm = ChatOpenAI(model="gpt-4o-mini")
wallet_data = None
if os.path.exists(wallet_data_file):
with open(wallet_data_file) as f:
wallet_data = f.read()
# Configure CDP Agentkit Langchain Extension.
values = {}
if wallet_data is not None:
# If there is a persisted agentic wallet, load it and pass to the CDP Agentkit Wrapper.
values = {"cdp_wallet_data": wallet_data}
agentkit = CdpAgentkitWrapper(**values)
# persist the agent's CDP MPC Wallet Data.
wallet_data = agentkit.export_wallet()
with open(wallet_data_file, "w") as f:
f.write(wallet_data)
# Initialize CDP Agentkit Toolkit and get tools.
cdp_toolkit = CdpToolkit.from_cdp_agentkit_wrapper(agentkit)
tools = cdp_toolkit.get_tools()
# Store buffered conversation history in memory.
memory = MemorySaver()
config = {"configurable": {"thread_id": "CDP Agentkit Chatbot Example!"}}
# Create ReAct Agent using the LLM and CDP Agentkit tools.
return create_react_agent(
llm,
tools=tools,
checkpointer=memory,
state_modifier=(
"You are a helpful agent that can interact onchain using the Coinbase Developer Platform AgentKit. "
"You are empowered to interact onchain using your tools. If you ever need funds, you can request "
"them from the faucet if you are on network ID 'base-sepolia'. If not, you can provide your wallet "
"details and request funds from the user. Before executing your first action, get the wallet details "
"to see what network you're on. If there is a 5XX (internal) HTTP error code, ask the user to try "
"again later. If someone asks you to do something you can't do with your currently available tools, "
"you must say so, and encourage them to implement it themselves using the CDP SDK + Agentkit, "
"recommend they go to docs.cdp.coinbase.com for more information. Be concise and helpful with your "
"responses. Refrain from restating your tools' descriptions unless it is explicitly requested."
),
), config
def reward_user(agent_executor, config, prompt):
for chunk in agent_executor.stream(
{"messages": [HumanMessage(content=prompt)]}, config
):
if "agent" in chunk:
print(chunk["agent"]["messages"][0].content)
elif "tools" in chunk:
print(chunk["tools"]["messages"][0].content)
print("-------------------")
async def fetch_messages(start_time, end_time):
CHANNEL_NAME = "general"
result = ""
for guild in bot.guilds:
for channel in guild.text_channels:
if channel.name == CHANNEL_NAME:
result += f'Channel :{channel.name} ({start_time.date()} ~ {end_time.date()})--------------\n'
try:
async for msg in channel.history(limit=None, after=start_time, before=end_time, oldest_first=True):
if msg.author.bot:
continue # Skip bot messages
user_wallet = USER_WALLETS_ADDRESS.get(msg.author.name) or "0x0000000000000000000000000000000000000000"
text = f"{msg.author.name}({user_wallet}) : {msg.content}\n"
result += text
except Exception as e:
print(f"Could not read channel {channel.name}: {e}")
result += "--------------------------------------------------------\n"
return result
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
# print with green color
# print("\033[92m" + f"Logged in discord as {bot.user.name}")
print("\033[92m" + f"Logged in discord as {bot.user.name}" + "\033[0m")
utc_now = datetime.now(timezone.utc)
yesterday = utc_now - timedelta(days=1)
start_of_yesterday = datetime(yesterday.year, yesterday.month, yesterday.day, 0, 0, tzinfo=timezone.utc)
channel_text = await fetch_messages(start_of_yesterday, start_of_yesterday + timedelta(days=1))
# Generate agent prompt
print("\033[92m" + "Generating Agent Prompt..." + "\033[0m")
prompt = f"{PROMPT_BEGINNING_TEXT}\n{channel_text}"
print (prompt)
print("\033[92m" + "Starting Agent..." + "\033[0m")
agent_executor, config = initialize_agent()
reward_user(agent_executor=agent_executor, config=config, prompt=prompt)
print("\033[92m" + "Agent Finished." + "\033[0m")
await bot.close()
bot.run(DISCORD_BOT_TOKEN)
Komlock lab エンジニア募集中
Web3の未来を共創していきたいメンバーを募集しています!!
気軽にDM等でお声がけください。
Komlock labの企業アカウント
PR記事とCEOの創業ブログ
Discussion