AttributeError: module 'embed storage' has no attribute 'help_command' - python

I have this module I made for a discord.py bot (not a COG though). It clearly has the function "help_command" defined but whenever I try to run it it gives me the above error. I couldn't wrap my head around it so I thought it might worth it to ask the community.
discord_main.py
import discord
from discord.ext import commands
import gsheet
import os
import embed_storage
async def help(ctx, argument='Helping'):
await ctx.send(embed=embed_storage.help_command('stargazer', argument))
embed_storage.py
import discord
from cogs.points import points_help_dict
from discord_main import help_dictionary
import gsheet
def help_command(cog_name: str, command: str):
if cog_name == 'stargazer':
use_dict = help_dictionary
title = 'Help'
description = 'Learn how the Stargazer Bot works'
footer_message = 'Prefix for this bot is \'a\''
else:
raise UnboundLocalError(
"Yeh this part of the code should have never run.")
command = command.lower()
if command in use_dict:
title = command.title()
description = use_dict[command]
field = False
help_command_embed = discord.Embed(
title=title,
description=description,
colour=discord.Colour.from_rgb(234, 255, 208)
)
return help_command_embed
Any help would be amazing. Also sorry for the dumb question. Just couldn't wrap my head around this silly error.
Edit: Tried Rolling back to my latest working version of the code and when I ran that. It still gave me the same error. So the error is not in the newly added code

I think the problem is that you are importing from discord_main in embed_storage and vice-versa.
You need to resolve this somehow or, if there is no other way, you could move the import into the function definition, e.g. in embed_storage.py:
def help_command(cog_name: str, command: str):
from discord_main import help_dictionary
if cog_name == 'stargazer':
use_dict = help_dictionary
# ...

Related

Why is the following error message popping up despite me having the correct version: "AttributeError: 'Graph' object has no attribute 'get_user_token'

With the use of this tutorial, https://learn.microsoft.com/en-us/graph/tutorials/python?tabs=aad, where I'm trying to get a Python app to function properly. It uses the Microsoft Graph API to access data on behalf of a user and is supposed to work, but it isn't working for me.
This is the following error message that pops up:
These are the files that I have:
Main:
When I press 1 it is supposed to prompt me to log in. I initially thought it was due to me using the wrong Python version, but even though I'm using the same version as in the tutorial, the same problem shows up. I'm using Python version 3.10.4 and pip version 20.0.2.
I tried to reproduce same process in my environment and got same error:
Console:
After I refer the document which you have posted in question and made changes with version of python, pip and msgraph-sdk because in msgraph-sdk they are using 1.0.0a2. as per document.
Make sure your graph is authenticating with your user.
Use the command:
Pip install msgraph-sdk==1.0.0a2
graph. py:
from configparser import SectionProxy
from kiota_authentication_azure.azure_identity_authentication_provider import (
AzureIdentityAuthenticationProvider)
from msgraph import GraphRequestAdapter, GraphServiceClient
from msgraph.generated.me.me_request_builder import MeRequestBuilder
from msgraph.generated.me.mail_folders.item.messages.messages_request_builder import (
MessagesRequestBuilder)
from msgraph.generated.me.send_mail.send_mail_post_request_body import SendMailPostRequestBody
from msgraph.generated.models.message import Message
from msgraph.generated.models.item_body import ItemBody
from msgraph.generated.models.body_type import BodyType
from msgraph.generated.models.recipient import Recipient
from msgraph.generated.models.email_address import EmailAddress
from async_auth import AsyncDeviceCodeCredential
class Graph:
settings: SectionProxy
device_code_credential: AsyncDeviceCodeCredential
adapter: GraphRequestAdapter
user_client: GraphServiceClient
def __init__(self, config: SectionProxy):
self.settings = config
client_id = self.settings['clientId']
tenant_id = self.settings['tenantId']
graph_scopes = self.settings['graphUserScopes'].split(' ')
self.device_code_credential = AsyncDeviceCodeCredential(client_id, tenant_id = tenant_id)
auth_provider = AzureIdentityAuthenticationProvider(
self.device_code_credential,
scopes=graph_scopes)
self.adapter = GraphRequestAdapter(auth_provider)
self.user_client = GraphServiceClient(self.adapter)
# </UserAuthConfigSnippet>
# <GetUserTokenSnippet>
async def get_user_token(self):
graph_scopes = self.settings['graphUserScopes']
access_token = await self.device_code_credential.get_token(graph_scopes)
return access_token.token
main. py
import asyncio
import configparser
from graph import Graph
async def main():
print('Python Graph Tutorial\n')
# Load settings
config = configparser.ConfigParser()
config.read(['config.cfg', 'config.dev.cfg'])
azure_settings = config['azure']
graph: Graph = Graph(azure_settings)
await greet_user(graph)
choice = -1
while choice != 0:
print('Please choose one of the following options:')
print('0. Exit')
print('1. Display access token')
print('2. List my inbox')
print('3. Send mail')
print('4. Make a Graph call')
try:
choice = int(input())
except ValueError:
choice = -1
if choice == 0:
print('Goodbye...')
elif choice == 1:
await display_access_token(graph)
elif choice == 2:
await list_inbox(graph)
elif choice == 3:
await send_mail(graph)
elif choice == 4:
await make_graph_call(graph)
else:
print('Invalid choice!\n')
async def greet_user(graph: Graph):
# TODO
return
async def display_access_token(graph: Graph):
token = await graph.get_user_token()
print('User token:', token, '\n')
async def list_inbox(graph: Graph):
# TODO
return
async def send_mail(graph: Graph):
# TODO
return
async def make_graph_call(graph: Graph):
# TODO
return
asyncio.run(main())
Console:
After I made changes in code the code executed perfectly and I got sign in link.
After signing in through web I can able to get the access token successfully.
Reference:
microsoftgraph/msgraph-training-python: Completed project for Build Python apps with Microsoft Graph (github.com)

Error: "self" is not defined error on VSCode on Ubuntu

I'm following a tutorial on understanding writing python publisher in ROS2. This is an example that I'm creating. The code does not seem to have any errors but in vscode, the self word is underlined in red and when I hover the mouse it shows that "self" is not defined. How can I resolve this issue in vscode?
I will add the code here
#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
from example_interfaces.msg import String
class RobotNewsStationNode(Node): #modify name
def __init__(self):
super().__init__("robot_news_station") #modify name
self.publisher_ = self.create_publisher(String, "robot_news", 10)
def publish_news(self):
msg = String()
msg.data = "Hello"
self.publisher_.publish(msg)
def main(args=None):
rclpy.init(args=args)
node = RobotNewsStationNode() #modify name
rclpy.spin(node)
rclpy.shutdown()
if __name__ == "__main__":
main()
This is the code error im having in vscode
As the error mentions, you are most likely mixing spaces/tabs.
Try delete all indentation untill that line, then use "tab" to indent your code, and be consistent about it i.e dont mix tabs and space.

telebot: How to take a massage in input here?

I don't know how to take a message in input here?
#bot.message_handler(commands=['tts'])
def send_text_request(message):
bot.reply_to(message, "Write a phrase")
#input...
You can manage it in two different ways:
Using custom_state, a new feature from recent releases.
After tts command you can set the state of user at 1, with:
bot.set_state(message.from_user.id, '1')
and create a new handler:
#bot.message_handler(state = '1'):
def new_function(message):
....
At the end of the code, add:
from telebot import custom_filters
bot.add_custom_filter(custom_filters.StateFilter(bot))
Source: https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/custom_states.py
Another way could be using register_next_step_handler, but honestly I used it only once and then I defined my personal states, because it's a mess. But I itroduce you to it anyway.
Define a new function that will handle the input from the user, so:
def function(message):
....
Change the code you already wrote with the following:
#bot.message_handler(commands=['tts'])
def send_text_request(message):
msg = bot.reply_to(message, "Write a phrase")
bot.register_next_step_handler(msg, function)
That's all!

How can I prevent getting an AttributeError after reloading a cog?

A more unusual question today, but maybe someone can help me.
I am working on a bot, which among other things has to do with music. The following problem:
If I change stuff in a cog and then reload it I always get an AttributeError: 'NoneType' object has no attribute 'XXXX' error for the particular command. Is there a way to fix/prevent this?
The error occurs when the bot is in a voice channel for example and then I reload the cog.
I query state for every command which has to do with music, is it maybe related to that?
state = self.get_state(ctx.guild)
Full function for get_state:
def get_state(self, guild):
"""Gets the state for `guild`, creating it if it does not exist."""
if guild.id in self.states:
return self.states[guild.id]
else:
self.states[guild.id] = GuildState()
return self.states[guild.id]
I tried to solve it with a try/except AttributeError, but of course that didn`t really work/the console still gave me the output.
Here is an example code:
#commands.command()
#commands.guild_only()
#commands.check(audio_playing)
#commands.check(in_voice_channel)
#commands.check(is_audio_requester)
async def loop(self, ctx):
"""Activates/Deactivates the loop for a song."""
state = self.get_state(ctx.guild)
status = state.now_playing.toggle_loop()
if status is None:
return await ctx.send(
embed=discord.Embed(title=":no_entry: Unable to toggle loop.", color=discord.Color.red()))
else:
return await ctx.send(embed=discord.Embed(
title=f":repeat: Loop: {'**Enabled**' if state.now_playing.loop else '**Disabled**'}.",
color=self.bot.get_embed_color(ctx.guild)))
And if I make changes in the cog, reload it and then try to run loop again I get the following error:
In loop:
File "C:\Users\Dominik\PycharmProjects\AlchiReWrite\venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Dominik\PycharmProjects\AlchiReWrite\cogs\music.py", line 220, in loop
status = state.now_playing.toggle_loop()
AttributeError: 'NoneType' object has no attribute 'toggle_loop'
(Same error for all the other commands)
Requested, we have the GuildState class:
class GuildState:
"""Helper class managing per-guild state."""
def __init__(self):
self.volume = 1.0
self.playlist = []
self.message_queue = []
self.skip_votes = set()
self.now_playing = None
self.control_message = None
self.loop = False
self.skipped = False
def is_requester(self, user):
return self.now_playing.requested_by == user
How would I overcome this error?
The bot joins on the command play URL and then I built in the following:
if not state.now_playing:
self._play_song(client, state, video)
_play_song is mainly defined the following:
def _play_song(self, client, state, song):
state.now_playing = song
# Other things are not relevant
When you reload the cog, the states dictionary in your cog will be empty. With state = self.get_state(ctx.guild), a new GuildState object is created. From the __init__ function of the GuildState class, self.now_playing is set to None.
Because of this, status = state.now_playing.toggle_loop() will throw an AttributeError as None has no attributes (in this case, no toggle_loop attribute).
If you want to get rid of these errors, you will need to set self.now_playing correctly to something that does have the needed attributes.
If you want to keep the states dictionary as is, you can save it before reloading your cog and restore it. The below example assumes that the cog class is named TestCog.
#client.command()
async def reload(ctx):
temp = client.get_cog('TestCog').states
client.reload_extension('cog')
client.get_cog('TestCog').states = temp
Note that this may break your cog if you change how GuildState is created, as you are restoring the previous version of states.

PubNub Exception in subscribe loop

I am trying to make a basic connection to PubNub and get some basic output with python. When I run the files in bash on windows I am getting a 504 error. I checked Pubnub and it says I am getting some usage which is strange. I am using pubnub 4.1.6
Any help with this would be much appreciated
Thank you so much for your help in advance
Please see the image to see the code I run and the error I am getting.
:
import time
from pubnub.pubnub import PubNub
from pubnub.pnconfiguration import PNConfiguration
from pubnub.callbacks import SubscribeCallback
pnconfig = PNConfiguration()
#pnconfig.ssl = True
pnconfig.subscribe_key = subscribe_key = 'XXX'
pnconfig.publish_key = publish_key ='XXX'
pubnub = PubNub(pnconfig)
'''Test Channel global variable'''
TEST_CHANNEL = 'TEST_CHANNEL'
pubnub.subscribe().channels([TEST_CHANNEL]).execute()
'''
Listen class extends SubscribeCallback and herits its behaviour
Must be put into a class as it's equipped to handle the different events that occur in this channel
'''
class Listener(SubscribeCallback):
def message(self, pubnub, message_object):
print(f'\n-- Incoming message object: {message_object}')
'''Instansiate an instance of message class within a call to add listener'''
pubnub.add_listener(Listener())
def main():
'''Sleep to ensure subsribe runs runs'''
time.sleep(1)
pubnub.publish().channel(TEST_CHANNEL).message({'foo': 'bar'}).sync()
if __name__=='main':
main()

Categories