@astigmatism

На replit mongodb не записывает данные, что делать?

import disnake
from disnake.ext import commands
from disnake import TextInputStyle
from typing import Optional
from pymongo import MongoClient

cluster = MongoClient(os.environ['mongodb1'])
collection = cluster.astikdb.ids1

class IDEAmodalcomment(disnake.ui.Modal):
	def __init__(self):
		components = [
			disnake.ui.TextInput(
				label = 'Комментарий к идее',
				placeholder = 'Напишите комментарий',
				custom_id = 'комментарий',
				style = TextInputStyle.long
			)
		]
		super().__init__(
			title = 'Комментарий',
			custom_id = 'титл',
			components = components
		)
	async def callback(self, inter: disnake.CommandInteraction):
		arg = inter.text_values['комментарий']
		role = disnake.utils.get(inter.guild.roles, name = 'IdeaManager')
		if not role in inter.author.roles:
			await inter.send('У вас нету роли для принятия идей')
		else:
			embed = disnake.Embed(colour = 0x2F3136)
			embed.set_author(name = f'Администратор {inter.author}', icon_url = inter.author.avatar)
			embed.add_field(name = 'Оставил комментарий', value = f'**{arg}**')
			await inter.send(embed = embed)

class IDEAbuttons(disnake.ui.View):
	def __init__(self):
		super().__init__(
			timeout = None
		)
	@disnake.ui.button(label = '✅', style = disnake.ButtonStyle.green)
	async def confirm(self, button: disnake.ui.Button, inter: disnake.CommandInteraction):
		role = disnake.utils.get(inter.guild.roles, name = 'IdeaManager')
		if not role in inter.author.roles:
			await inter.send('У вас нету роли для принятия идей', ephemeral = True)
		else:
			embed = disnake.Embed(colour = 0x2F3136)
			embed.set_author(name = f'Администратор {inter.author}', icon_url = inter.author.avatar)
			embed.add_field(name = 'Принял вашу идею', value = '✅')
			await inter.send(embed = embed)
	@disnake.ui.button(label = '❌', style = disnake.ButtonStyle.red)
	async def cancel(self, button: disnake.ui.Button, inter: disnake.CommandInteraction):
		role = disnake.utils.get(inter.guild.roles, name = 'IdeaManager')
		if not role in inter.author.roles:
			await inter.send('У вас нету роли для принятия идей', ephemeral = True)
		else:
			embed = disnake.Embed(colour = 0x2F3136)
			embed.set_author(name = f'Администратор {inter.author}', icon_url = inter.author.avatar)
			embed.add_field(name = 'Откланил вашу идею', value = '❌')
			await inter.send(embed = embed)
	@disnake.ui.button(label = 'Комментировать', style = disnake.ButtonStyle.gray, emoji = '✉️')
	async def comment(self, button: disnake.ui.Button, inter: disnake.CommandInteraction):
		role = disnake.utils.get(inter.guild.roles, name = 'IdeaManager')
		if not role in inter.author.roles:
			await inter.send('У вас нету роли для принятия идей', ephemeral = True)
		else:
			await inter.response.send_modal(modal = IDEAmodalcomment())

class IDEAmodal(disnake.ui.Modal):
	def __init__(self):
		components = [
			disnake.ui.TextInput(
				label = 'Идея',
				placeholder = 'Напишите идею',
				custom_id = 'идея',
				style = TextInputStyle.long
			)
		]
		super().__init__(
			title = 'Отправка идеи',
			custom_id = 'титл',
			components = components
		)
	async def callback(self, inter: disnake.CommandInteraction):
		arg = inter.text_values['идея']
		channel1 = collection.find_one({"guild_id": inter.guild.id})["id_channel"]
		channel2 = collection.find_one({"guild_id": inter.guild.id})["id_admin_channel"]
		send1 = disnake.utils.get(inter.guild.text_channels, id = channel1)
		send2 = disnake.utils.get(inter.guild.text_channels, id = channel2)
		if not send1 or send2 in inter.guild.text_channels:
			await inter.send('Канал для отправки идей отсутствует!', ephemeral = True)
		else:
			embed = disnake.Embed(colour = 0x2F3136)
			embed.set_author(name = f'Участник {inter.author}', icon_url = inter.author.avatar)
			embed.add_field(name = 'Отправил идею', value = f'Идея:\n**{arg}**')
			c = await send1.send(embed = embed, view = IDEAbuttons())
			await inter.send('Идея отправлена!', ephemeral = True)
			await c.add_reaction('✅')
			await c.add_reaction('❌')
			c = await send2.send(embed = embed)
			await c.add_reaction('✅')
			await c.add_reaction('❌')

class IDEA(commands.Cog):
	def __init__(self, bot):
		self.bot = bot
		self.cluster = MongoClient(os.environ['mongodb1'])
		self.collection = self.cluster.astikdb.ids1

	@commands.Cog.listener()
	async def on_ready(self):
		print('IDEA cog on_ready')

	@commands.command()
	@commands.has_permissions(administrator = True)
	async def set_idea(self, ctx, channel_id1: int = None, channel_id2: int = None):
		if channel_id1 is None:
			await ctx.send('Укажите айди канала идей, и айди канала принятия идей')
		elif channel_id2 is None:
			await ctx.send('Укажите айди канала идей, и айди канала принятия идей')
		else:
			idea = {
				"guild_id": ctx.guild.id,
				"id_channel": channel_id1,
				"id_admin_channel": channel_id2
			}
			self.collection.insert_one(idea)
			await ctx.send('Готово!')	

	@commands.slash_command(name = 'idea', description = 'Команда для отправки идеи')
	async def idea_slash(self, inter):
		modal = IDEAmodal()
		await inter.response.send_modal(modal = modal)

def setup(bot):
	bot.add_cog(IDEA(bot))

Когда я пытаюсь записать данные в базу, запустив бота на пк, то все работает. А когда я пытаюсь запустить это на replit (я использую его как хостинг), то выдает эту ошибку:
Command raised an exception: ServerSelectionTimeoutError: ac-ryjbj3e-shard-00-01.pw2w2rz.mongodb.net:27017: connection closed,ac-ryjbj3e-shard-00-00.pw2w2rz.mongodb.net:27017: connection closed,ac-ryjbj3e-shard-00-02.pw2w2rz.mongodb.net:27017: connection closed, Timeout: 30s, Topology Description: <TopologyDescription id: 64547e677eb3f89edc50e4b5, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('ac-ryjbj3e-shard-00-00.pw2w2rz.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-ryjbj3e-shard-00-00.pw2w2rz.mongodb.net:27017: connection closed')>, <ServerDescription ('ac-ryjbj3e-shard-00-01.pw2w2rz.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-ryjbj3e-shard-00-01.pw2w2rz.mongodb.net:27017: connection closed')>, <ServerDescription ('ac-ryjbj3e-shard-00-02.pw2w2rz.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-ryjbj3e-shard-00-02.pw2w2rz.mongodb.net:27017: connection closed')>]>
  • Вопрос задан
  • 40 просмотров
Пригласить эксперта
Ответы на вопрос 1
mayton2019
@mayton2019
Bigdata Engineer
Никто не захочет разбираться с твоими ботами.
Если ты пишешь что проблема в Монго - то вот бери 100% рабочий пример

https://www.mongodb.com/languages/python

Там 4 строчки которые демонстрируют создание коннекта получение БД и вставку документа.

Деплой 4 строчки на replit и доказывай что они не работают. Все остальное что ты привел - это рандомный
шум который мешает пониманию главной причины. Root cause.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы