python replit database throwing typeError - python

I was trying to make functions to save, get, and get all for the Replit Python database. It doesn't work and I can't find out why.
Get all function:
def loadAll(user):
if user in db.keys():
return db[user]
if user not in db.keys():
db[user] = {}
return db[user]
It throws an error at return db[user].
This is the code that fires the function (I'm using the discord.py commands extension.):
#bot.command(name = "getMyData")
async def getUserData(ctx):
await ctx.send(ctx.author)
await ctx.send(loadAll(ctx.author))
The error message says:
TypeError: quote_from_bytes() expected bytes

I solved it by changing the database key to not just be the user.

Replit Database doesn't support integers as keys. Stringify the key beforehand.

Related

Discord Bot checking if key from json present in message

from discord.ext import commands
import json
with open(r"C:\Users\intel\Desktop\rijalbot\rijaldata\narrators.json") as f:
narrators = json.load(f)
class cmds(commands.Cog):
def __init__(self, client):
self.bot = client
#commands.command()
async def rijal(self, ctx, message):
if narrators.keys() in ctx.message:
val = narrators.get(ctx.message)
if val == "weak":
await ctx.send("True")
narrators.json
{"a": "weak"}
I want my discord bot to check if my message contains a key from a json, but everytime I run it, and execute the [!rijal a] command, it does nothing, it should send "True"
narrators.keys() is a view of all keys in the dictionary. The message is a string, so narrators.keys() will never be in message.
narrators.get(message) also won't work if the message isn't exactly the same. You're using in, so you're just looking for substrings. For example: "a" is in "another", but {"a": "weak"}.get("another") won't find a match, because "another" isn't inside of the dictionary.
If you want substrings, loop over the keys instead. To get the value, get it from the dict using the corresponding key instead of the message, as that won't work (as described above). An alternative is to loop over both the keys & values at the same time using items.
If you want full matches, get() will return None if nothing was found.
PS consider using an actual database instead of a JSON file

'NoneType' object has no attribute 'node' Lavalink

I'm trying to make a music bot in python, and I get this error:
AttributeError: 'NoneType' object has no attribute 'node'
I suspect that this part of the code is causing this problem:
#cog_ext.cog_slash(name="play", guild_ids=guild_ids, description="Play song")
async def play(self, ctx, *, query: str):
""" Searches and plays a song from a given query. """
# Get the player for this guild from cache.
player = self.bot.lavalink.player_manager.get(ctx.guild.id)
# Remove leading and trailing <>. <> may be used to suppress embedding links in Discord.
query = query.strip('<>')
# Check if the user input might be a URL. If it isn't, we can Lavalink do a YouTube search for it instead.
# SoundCloud searching is possible by prefixing "scsearch:" instead.
if not url_rx.match(query):
query = f'ytsearch:{query}'
# Get the results for the query from Lavalink.
results = await player.node.get_tracks(query)
# Results could be None if Lavalink returns an invalid response (non-JSON/non-200 (OK)).
# ALternatively, resullts['tracks'] could be an empty array if the query yielded no tracks.
if not results or not results['tracks']:
return await ctx.send('Nothing found!')
Let me know if anyone needs more code, I don't want to spam all the code if it is not needed

Sqlite3 Flask discord bot dashboard. TypeError: "NoneType object is not subscriptable

So, i'm making a discord bot dashboard and, in the guild settings, I want to show if a category if enabled or desabled. And I maked this code:
#app.route("/serveurs/<int:serveur_id>")
def serveur(serveur_id):
if 'token' not in session:
return redirect("https://discord.com/api/oauth2/authorize?client_id=787982190776287282&redirect_uri=https%3A%2F%2FMEE0-1.devteaming.repl.co%2Foauth%2Fdiscord&response_type=code&scope=identify%20guilds")
serveur_info = get_serveur_info(serveur_id)
if not serveur_info:
return redirect('/dashboard')
with sqlite3.connect("dashboard.sqlite3") as db:
cursor = db.cursor()
cursor.execute(f"SELECT * FROM dashboardconfig WHERE guilds_id = {serveur_info['id']}")
data = cursor.fetchone()
print(data)
mod = bool(data[2])
music = bool(data[2])
fun = bool(data[2])
return render_template("serveur.html", serveur=serveur_info, mod=mod, music=music, fun=fun)
When I restart the server and I go on the endpoint it raise me this error in the terminal:
TypeError: "NoneType object is not subscriptable"
I'm pretty sure the error is in the data variable but I don't know how fix it. If anyone can help me, thanks.
PS: I make all the functions, files etc... Don't worry ;).

'Context' object has no attribute 'reddit' Discord.PY

I'm trying to add a .reddit command to my bot. This is my code:
#client.command(name="random", aliases=["reddit"])
async def _random(ctx, subreddit: str = ""):
reddit = None
if reddit_app_id and reddit_app_secret:
reddit = praw.Reddit(client_id=reddit_app_id,client_secret=reddit_app_secret,user_agent="MASTERBOT:%s1.0" % reddit_app_id)
if reddit:
submissions = reddit.subreddit(subreddit).hot()
submission = next(x for x in submissions if not x.stickied)
await ctx.send(submissions.url)
I have everything imported, everything seemed fine until I got this error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Command' object has no attribute 'randint'
As I understood, the program has no idea what a randint is. I checked if I've made a typo, but no. Everything seemed fine. I was getting an antoher error on the same command but I managed to fix it. But this one got me and I need your help.
These are the new errors:
AttributeError: 'coroutine' object has no attribute 'url'
.
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Do you have the command in a Cog (class)?
If you don't, then you should remove self, as it'll assume that that's the name of the context object.
#client.command(name="random", aliases=["reddit"])
async def _random( ctx, subreddit: str = ""):
reddit = None
if reddit_app_id and reddit_app_secret:
reddit = praw.Reddit(client_id=reddit_app_id,client_secret=reddit_app_secret,user_agent="MASTERBOT:%s1.0" % reddit_app_id)
if reddit:
chosen_subreddit = reddit_enabled_meme_subreddits[0]
if subreddit:
if subreddit in reddit_enabled_meme_subreddits:
chosen_subreddit = subreddit
submissions = reddit.subreddit(chosen_subreddit).hot()
post_to_pick = random.randint(1, 10)
for i in range(0, post_to_pick):
submission = next(x for x in submissions if not x.stickied)
await ctx.send(submission.url)
else:
await ctx.send("This is not working")
The issue is with the name of the command, random, as this is polluting the namespace of the random module. You're able to bypass this by renaming the command.
The async def random(.... is clashing with import random at the top of your code. You're able to set the name of the command with the name= keyword argument in the decorator. That's the name that people will be typing into discord.
Tried using your method of getting a random submission (minus the superfluous code, just the same logic), and it worked for me:
reddit = praw.Reddit(client_id="...", client_secret="...", user_agent="...")
#bot.command(name="reddit")
async def _reddit(ctx, subreddit: str = ""):
submissions = reddit.subreddit(subreddit).hot()
submission = next(x for x in submissions if not x.stickied)
await ctx.send(submission.url)
The only thing I can think of is making sure that you have the most up-to-date version of praw, and also if there's anything else in the command that you might be leaving out of the question, then that might be affecting it, although that's just speculation.
I'd say try making the command from the ground-up. Start off simple with something that works, and add to it line by line until something breaks. Then you'll know what's causing the RuntimeWarning and such.
Sorry for not having a clear-cut answer for this.

Python Telegram bot - KeyError after running for a few hours

I wrote a Telegram bot in Python, which is running on my Raspberry Pi (Raspbian). I eventually see an error after the bot has been running for a few hours.
Before I post the complete code, could someone please help me understand the error? I would like to run the bot indefinitely, or at least for multiple days, before I need to restart it.
The error is as follows:
Traceback (most recent call last):
File "/home/pi/Schreibtisch/StreamrPreisBot/telepot/loop.py", line 37, in run_forever
self._handle(msg)
File "/home/pi/Schreibtisch/StreamrPreisBot/streamrinfobot.py", line 32, in handle
command = msg['text']
KeyError: 'text'
Edit:
Following code is used:
def handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
Might this code solve the problem?
def handle(msg):
chat_id = msg['chat']['id']
command = msg.get('text')
Error says there is no text key inside msg dict. Maybe it's some special telegram message that has no text or there is a bug in you code that delete text key in some cases. You could use
command = msg.get('text')
To get None when there is no text. Or
command = msg.get('text', '')
To get empty string (i.e. '') when there is no text.
You could also check that there is a text inside msg or not with in operator:
if 'text' not in msg:
logger.error('bad message received!')
return
If you want to your service to be always up you should add some mechanism for automatic restart.
like in Python to restart after any error:
while True:
try:
logger.info("Starting bot")
run_bot()
except Exception:
logger.exception("Something bad happened. Restarting")
I also suggest to log errors in a file or services such as Sentry to investigate why there is no text afterwards.
A KeyError is raised when a value is requested from a dict but the key does not exist in the dictionary.
So, in your case, the msg dictionary does not have the key text.
You should inspect your code to ensure that the msg dictionary contains a value associated with the key text. Or, if you expect that msg will sometimes not contain the key text, you should instead access the dictionary with the get method, which never raises a KeyError. See the docs for more information.

Categories

Resources