在Railway部署Discord预测机器人:CLUSTER_LINK等变量咨询
如何配置Predictions-Bot中MongoDB相关的CLUSTER_LINK、CLUSTER_ELEMENT、DB_ELEMENT环境变量?
我是Discord机器人与Python新手,正尝试在Railway.app上部署GitHub上的Predictions-Bot。已配置Token、Guild、Channel1-3等环境变量,但不清楚CLUSTER_LINK、CLUSTER_ELEMENT、DB_ELEMENT这三个MongoDB相关变量的含义及配置方式,希望得到帮助。我已学习Python环境变量及MongoDB基础知识,相关代码片段如下:
import time import discord import os from discord.ext import commands from discord.ext.commands import has_permissions, MissingPermissions import Functions from threading import Timer import random from pymongo import MongoClient import math import datetime # global vars intents = discord.Intents.all() believePool, doubtPool, globalDict, guildMember, payOutPool = {}, {}, {}, {}, {} global posts, cluster startComDescription = "If the title/blv/dbt is more than one word use \"\". t is the time and is in seconds i.e. t = 120 = 2 minutes (Only admins can use)" giveComDescription = "Gives points to specific member, you have to type their discord NAME (Only admins can use)." refundComDescription = "Refunds points and stops prediction (Only admins can use)." wonComDescription = "Sets win after a prediction has started, side = \"blv\" or \"dbt\" (Only admins can use)." TOKEN, GUILD, CHANNEL1, CHANNEL2, CHANNEL3 = os.getenv("Token"), os.getenv("Guild"), os.getenv("Channel1"), os.getenv("Channel2"), os.getenv("Channel3") CLUSTER_LINK, CLUSTER_ELEMENT, DB_ELEMENT = os.getenv("ClusterLink"), os.getenv("PointsData"), os.getenv("UserPoints") cluster = MongoClient(CLUSTER_LINK)
三个MongoDB相关变量的含义
- CLUSTER_LINK:MongoDB集群的连接字符串,是代码与远程MongoDB数据库建立连接的核心凭证。代码中
cluster = MongoClient(CLUSTER_LINK)就是通过这个字符串初始化数据库连接。 - CLUSTER_ELEMENT:对应MongoDB中的数据库名称。从代码默认变量名
PointsData可以看出,这个数据库用于存储预测相关的积分数据。 - DB_ELEMENT:对应MongoDB数据库下的集合名称。默认变量名
UserPoints说明这个集合用来存储单个用户的积分信息。
配置步骤
获取CLUSTER_LINK
- 若使用MongoDB Atlas:登录后进入目标集群,点击「Connect」→「Connect your application」,选择Python驱动版本,复制生成的连接字符串,将字符串中的
<password>替换为数据库用户的密码即可。 - 若使用Railway自带的MongoDB服务:在Railway项目中添加MongoDB插件后,进入该服务的「Variables」页面,找到
DATABASE_URL,其值就是你需要的CLUSTER_LINK。
- 若使用MongoDB Atlas:登录后进入目标集群,点击「Connect」→「Connect your application」,选择Python驱动版本,复制生成的连接字符串,将字符串中的
设置CLUSTER_ELEMENT和DB_ELEMENT
- CLUSTER_ELEMENT可以直接使用代码默认的
PointsData,也可以自定义名称(MongoDB会自动创建不存在的数据库)。 - DB_ELEMENT同样可以用默认的
UserPoints,后续代码会自动在指定数据库下创建该集合(若不存在)。
- CLUSTER_ELEMENT可以直接使用代码默认的
在Railway中配置环境变量
- 打开Railway项目的「Variables」页面,添加以下三个变量:
ClusterLink:粘贴获取到的MongoDB连接字符串PointsData:填入你设置的数据库名称(如PointsData)UserPoints:填入你设置的集合名称(如UserPoints)
- 打开Railway项目的「Variables」页面,添加以下三个变量:
内容的提问来源于stack exchange,提问作者NickyboyJP
相关产品推荐
相关产品推荐

