Issue with motor (discord.py) - discord

I'm currently using motor (async wrapper for pymongo) in my discord bot and I get this error
py
Ignoring exception in on_message
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.9/site-packages/discord/client.py", line 361, in _run_event
await coro(*args, **kwargs)
File "/workspace/cogs/helpful.py", line 177, in message_increment
data = await self.message_database.find_one({"_id": message.author.id})
RuntimeError: Task <Task pending name='discord.py: on_message' coro=<Client._run_event() running at /app/.heroku/python/lib/python3.9/site-packages/discord/client.py:361>> got Future <Future pending cb=[_chain_future.<locals>._call_check_cancel() at /app/.heroku/python/lib/python3.9/asyncio/futures.py:384]> attached to a different loop
Does anyone know why gets raised?
Line 177:
#commands.Cog.listener("on_message")
async def message_increment(self, message: discord.Message):
if message.author.bot:
return
data = await self.message_database.find_one({"_id": message.author.id})
if data is None:
await self.message_database.insert_one(
{"_id": message.author.id, "messages": 1, "name": str(message.author)}
)
if data is not None:
await self.message_database.update_one(
{"_id": message.author.id}, {"$inc": {"messages": 1}}
)
await self.message_database.update_one(
{"_id": message.author.id}, {"$set": {"name": str(message.author)}}
)

Alright I've figured out how to solve my error. All I needed to do was move my AsyncIOMotorClient instance to somewhere where my bot loop exists. Thanks everyone that tried to help me!

Related

Is Discord User Id too big to send dm too?

I'm making a slash command that can send dms to a specific user id that's been determined by a command argument. It works for specific user ids, but not all of them, including mine my alt account. Is it some permission thing or is the user id out of range?
My code
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
# importing environmental vars
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
GUILD = os.getenv("DISCORD_GUILD")
APP_ID = os.getenv("APP_ID")
PUB_KEY = os.getenv("PUBLIC_KEY")
GUILD_ID = os.getenv("GUILD_ID")
GENERAL_CHAN_ID = os.getenv("CHANNEL_GENERAL_ID")
#finished importing .env vars
intents = discord.Intents.all()
activity = discord.Activity(name="being awesome losers", type = discord.ActivityType.streaming)
bot = discord.Bot(intents=intents, activity=activity)
#bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
#bot.slash_command(description="sends message to someone still testing",guild_ids=[GUILD_ID])
async def send_message(ctx, user_id: str, message: str):
user = bot.get_user(int(user_id))
await user.send(message)
await ctx.respond("Message sent successfully!", ephemeral = True)
#bot.event
async def on_message(message):
channel = bot.get_channel(956302622170701946)
if message.content.startswith("help"):
await message.author.send('👋')
bot.run(TOKEN)
When I input an ID that doesn't work it gives me this traceback
AttributeError: 'NoneType' object has no attribute 'send'
Traceback (most recent call last):
File "C:\Users\Rayan\source\repos\DBot\DiscordBot\lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
File "C:\Users\Rayan\source\repos\DBot\DiscordBot\lib\site-packages\discord\commands\core.py", line 980, in _invoke
await self.callback(ctx, **kwargs)
File "c:\Users\Rayan\source\repos\DBot\main.py", line 56, in send_message
await user.send(message)
AttributeError: 'NoneType' object has no attribute 'send'
Help is greatly appreciated! Thank you!
I do not think the issue is that the ID is out of range. It's simply that the user is not in the cache.
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
# importing environmental vars
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
GUILD = os.getenv("DISCORD_GUILD")
APP_ID = os.getenv("APP_ID")
PUB_KEY = os.getenv("PUBLIC_KEY")
GUILD_ID = os.getenv("GUILD_ID")
GENERAL_CHAN_ID = os.getenv("CHANNEL_GENERAL_ID")
#finished importing .env vars
intents = discord.Intents.all()
activity = discord.Activity(name="being awesome losers", type = discord.ActivityType.streaming)
bot = discord.Bot(intents=intents, activity=activity)
#bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
#bot.slash_command(description="sends message to someone still testing",guild_ids=[GUILD_ID])
async def send_message(ctx, user_id: str, message: str):
user = await bot.fetch_user(int(user_id))
await user.send(message)
await ctx.respond("Message sent successfully!", ephemeral = True)
#bot.event
async def on_message(message):
channel = bot.get_channel(956302622170701946)
if message.content.startswith("help"):
await message.author.send('👋')
bot.run(TOKEN)
This will always fetch the user and therefore will be able to DM everyone, even not in the cache.

Error with discord bot 1.7.3 giving very long error

I was trying to make a discord chat bot but I got this error I am not sure what to do by the way I am using discord 1.7.3 here is the code by the way the DISCORD KEY and OPENAI-KEY are not the problem those are to hide my openai key and discord bot key:
import discord
import asyncio
import openai
import os
openai.api_key = os.environ.get('OPENAI-KEY')
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
elif message.content.startswith('$chat'):
response = openai.Completion.create(
engine="davinci",
prompt=message.content[5:],
max_tokens=100,
temperature=0.9,
top_p=1,
n=1,
stream=False,
logprobs=None,
stop=["\n"],
)
await message.channel.send(response['choices'][0]['text'])
client.run(os.environ.get('DISCORD-TOKEN'))
Here is the error I am getting:
import discord
import asyncio
import openai
import os
openai.api_key = os.environ.get('OPENAI-KEY')
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
elif message.content.startswith('$chat'):
response = openai.Completion.create(
engine="davinci",
prompt=message.content[5:],
max_tokens=100,
temperature=0.9,
top_p=1,
n=1,
stream=False,
logprobs=None,
stop=["\n"],
)
await message.channel.send(response['choices'][0]['text'])
client.run(os.environ.get('DISCORD-TOKEN'))
Here is the error I am getting
Traceback (most recent call last):
File "c:\Users\Private\OneDrive\Desktop\Pro\GitHub Repo\Discord_chat_bot\Bot.py", line 35, in <module>
client.run(os.environ.get('DISCORD-TOKEN'))
File "C:\Users\Private\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\Private\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\Private\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 665, in start
await self.login(*args, bot=bot)
File "C:\Users\Private\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'NoneType' object has no attribute 'strip'
I was expecting for it to work if I try this code in 2.0.0 discord it give a different error
The reason I am using 1.7.3 not 2.0.0 is because I had a different error and to fix it I had to switch to 1.7.3
Error on this line:
client.run(os.environ.get('DISCORD-TOKEN'))
The token you are passing in is None because os.environ.get('DISCORD-TOKEN') returns None.
You could have forgot to set your environment variable or you had it in a .env file. If you have it in a .env file, please load it:
from dotenv import load_dotenv
load_dotenv()

Google Assistant Smart Home may return error 500 when doing Request Sync

I am doing Request Sync for my users because I implemented a new device type.
For some users it succeeds, but for some users I got errors with status 500 as a response of Request Sync like below.
{
"error": {
"code": 500,
"message": "Internal error encountered.",
"status": "INTERNAL"
}
}
I noticed the following rule about this error
If the error occurs in the Request Sync for a user, the same result will occur if I try the same thing for the same user immediately afterwards.
However, if I make a request to that user a day later, the request to the user may be successful.
I looked at the following document, but there is no description about the 500 status error.
https://developers.google.com/assistant/smarthome/develop/request-sync
Do you know why this is happening? Also, if you know the solution, please let me know.
Edited on April 22, 2021
The script is the following. It is written in NodeJS.
const smarthome = require('actions-on-google');
const app = smarthome.smarthome({
jwt: require('config.json')
});
const agentUserIds = ["xxxxx", "yyyyy"];
const sleep = msec => new Promise(resolve => setTimeout(resolve, msec));
const requestSync = async () => {
for (userId of agentUserIds) {
await app.requestSync(userId)
.then(() => {
console.log("Request sync success");
})
.catch(err => {
console.log("Request sync error");
console.error(err);
});
await sleep(1000);
}
};
requestSync();
As a result, I got the following output. It succeeds for some specific users and fails for some specific users.
Request sync error
{
"error": {
"code": 500,
"message": "Internal error encountered.",
"status": "INTERNAL"
}
}
Request sync success
Hi Can you check you are sending the correct API-Key in the Header, related to the users / agenuserId for which the Call is getting failed.

How to get a bot to save the message after a trigger word (discord.py)

I'm trying to get my bot to respond to a message sent after a trigger word, but all it does is send me the following error: AttributeError: 'generator' object has no attribute 'content'. Here is my code:
#client.event
async def on_message(message):
if message.content == "report":
await message.author.send("Type your report below")
def check(m):
return m.guild == None and m.author == message.author
try:
response = client.wait_for("message", check=check)
except asyncio.TimeoutError:
await message.author.send("Uh-oh, the request timed out! Try again.")
else:
content = response.content
Thanks in advance!
client.wait_for is a coroutine function. That means, in order to use it, you have to await it.
You just have to do:
response = await client.wait_for("message", check=check)

Error using commands.Greedy in Discord.py Rewrite

Whenever I try to use commands.Greedy I keep get AttributeError: module 'discord.ext.commands' has no attribute 'Greedy'. Here's my code:
#client.command(description="Kicks user", usage="[#user(s)]", brief="Kicks user")
#commands.has_role(settings.admin_role_name)
async def kick(self, ctx, targets: commands.Greedy[discord.Member], *reason: str):
for target in targets:
await target.kick(reason="{} ({}) used .kick command with the reason {}".format(ctx.message.author.name, ctx.message.author.id, reason))
await ctx.send("<#{}> kicked <#{}>\n**Reason:** {}".format(ctx.message.author.id, target.id, reason))
#client.command(description="Bans user", usage="[#user]", brief="Bans user")
#commands.has_role(settings.admin_role_name)
async def ban(self, ctx, targets: commands.Greedy[discord.Member], *reason: str):
for target in targets:
await target.ban(reason="{} ({}) used .kick command with the reason {}".format(ctx.message.author.name, ctx.message.author.id, reason))
await ctx.message.channel.send("{} banned <#{}>\n**Reason:** {}".format(ctx.message.author.id, target.id, reason))
My discord version is discord.py 1.0.0a1561+g53433bc
I reinstalled discord.py, turns out I had a old version that didn't have this

Resources