How to fetch values from dict - python

I am implementing a chat client gui whith server-push functionality. The messages that will be sent will look like this:
yourMessage = {'name': 'David', 'text': 'hello world'}
I recieve a server-push by a call to the streamHandler
def streamHandler(incomingData):
if incomingData["event"] == "put":
if incomingData["path"] == "/":
if incomingData["data"] != None:
for key in incomingData["data"]:
message = incomingData["data"][key]
handleMessage(message)
else:
message = incomingData["data"]
handleMessage(message)
Then I have the function handleMessage that should retrieve the values of name and text:
def handleMessage(message):
for key in message.values():
printToMessages(key)
But now I get this Error: 'str' object has no attribute 'values' I have tried making message to dict but with no success, any ideas?

Perhaps the message parameter is a json string.
If so you can have:
import json
def handleMessage(text):
message = json.loads(text)
for key in message.values():
printToMessages(key)

Related

Simple dictionary with Telegram Bot

I'm working on a simple dictionary accessible through a telegram bot.
This is my code in Python, what am I wrong?
#!/usr/bin/python3
import telebot
API_TOKEN = 'MY TELEGRAM TOKEN'
bot = telebot.TeleBot(API_TOKEN)
Dizio={'cat': 'blue', 'dog': 'red', 'fly': 'black'}
# Handle all other messages with content_type 'text' (content_types defaults to ['text'])
#bot.message_handler(func=lambda message: True)
def echo_message(message):
if message.text.lower() in Dizio.keys():
res = Dizio.get('translate', {}).get('=')
bot.send_message(message.chat.id, message.text(res))
else:
bot.send_message(message.chat.id, 'not found')
bot.infinity_polling()
There are a couple of problems inside the echo_message function:
You aren't using correctly the dict.get method;
you are calling message.text, this is a string, and you can't call strings;
Here's how i would resolve this problem, we can use the fact that dict.get allows us to provide a default value if the key is missing:
def echo_message(message):
res = Dizio.get(message.text.lower(), "not found")
bot.send_message(message.chat.id, res)

Django API with multiple calls using try, except

I am trying to make an API endpoint that will take input like http://127.0.0.1:8000/getslots?car_number=3and give output as car_number or slot_parking. Here is what I have done:
slots = {'ka9865': 1, 'ka9866': 2, 'ka9867': 3}
def get_car(request):
if request.method == 'GET':
try:
car_number = request.GET['car_number']
for key,value in slots.items():
if key == car_number:
car_slot = value
response = json.dumps([{'slot': car_slot}])
except (UnboundLocalError):
slot = request.GET['car_number']
for key,value in slots.items():
if value == slot:
car_number1 = key #not entering inside this loop
response = json.dumps([{ 'car_number': car_number1}])
except:
response = json.dumps([{ 'Error': 'No car with that name/slot'}])
return HttpResponse(response, content_type='text/json')
But I am getting error of UnboundLocalError: local variable 'response' referenced before assignment
I am not able to figure out how to do this and also please suggest me if there is any better way of implementing this.
Thank you.
You need to creatwe response already before otherwise the variable will be just in the namespace of the exception block.
slots = {'ka9865': 1, 'ka9866': 2, 'ka9867': 3}
def get_car(request):
response = None # Create default reponse here
if request.method == 'GET':
#...

I want to update a dictionary/json key instead of appending a new one?

Alright, So I am using discord.py and JSON and I am trying to make a ticket counter, the client refuses to use a database so I have to use JSON. But every time the code updates the file it create a second key and then it uses that key instead of the first one. If anyone wants to see it happen in action friend me (Jpac14#8237) and I'll show you what happens. I will also attach my code and the JSON file.
Also do you think I could you Collections Module for this.
Code:
from discord.ext import commands
import discord
import json
class TicketSystem(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.create_ticket_msgs = []
#commands.Cog.listener()
async def on_reaction_add(self, reaction, user):
for create_ticket_msg in self.create_ticket_msgs:
if reaction.message.id == create_ticket_msg.id and user != self.bot.user:
await reaction.message.channel.send(f"{user} reacted")
await reaction.message.remove_reaction("📩", user)
ticket_counter_dict = {}
try:
with open("json/ticket_counter.json", "r") as ticket_counter_json:
ticket_counter_dict = json.load(ticket_counter_json)
except json.JSONDecodeError:
print("JSONDecodeError")
current_ticket_counter = ticket_counter_dict.get(str(reaction.message.guild.id))
if current_ticket_counter == None:
current_ticket_counter = 1
ticket_catergory = discord.utils.get(reaction.message.guild.categories, name="Tickets")
if reaction.message.guild.id == 660156957486874645:
support_team_role = discord.utils.get(reaction.message.guild.roles, name="Staff")
else:
support_team_role = discord.utils.get(reaction.message.guild.roles, name="Support")
ticket_channel_overwrites = {
support_team_role: discord.PermissionOverwrite(read_messages=True),
user: discord.PermissionOverwrite(read_messages=True),
reaction.message.guild.default_role: discord.PermissionOverwrite(read_messages=False)
}
users_ticket_channel = await ticket_catergory.create_text_channel(f"ticket-{current_ticket_counter}", overwrites=ticket_channel_overwrites)
current_ticket_counter += 1
ticket_counter_dict.update({reaction.message.guild.id: current_ticket_counter})
with open("json/ticket_counter.json", "w") as ticket_counter_json:
json.dump(ticket_counter_dict, ticket_counter_json)
embedMessage = discord.Embed(description="Support will be with you shortly.\nTo close the ticket type ?close", color=discord.colour.Colour.green())
embedMessage.set_footer(text=f"Created By Nexus Developments - https://discord.gg/YmdugDf", icon_url="https://i.imgur.com/MRBsIpe.png")
await users_ticket_channel.send(embed=embedMessage)
#commands.command(name="ticketmsg")
async def send_create_ticket_msg(self, ctx, channel: discord.TextChannel):
embedMessage = discord.Embed(title="Create A Ticket", description="To create a ticket react with 📩", timestamp=ctx.message.created_at, color=discord.colour.Colour.green())
embedMessage.set_footer(text=f"Created By Nexus Developments - https://discord.gg/YmdugDf", icon_url="https://i.imgur.com/MRBsIpe.png")
create_ticket_msg = await channel.send(embed=embedMessage)
await create_ticket_msg.add_reaction("📩")
self.create_ticket_msgs.append(create_ticket_msg)
def setup(bot):
bot.add_cog(TicketSystem(bot))
JSON File:
{"665930890039394305": 6, "665930890039394305": 7}
reaction.message.guild.id is an int.
When you write ticket_counter_dict.update({reaction.message.guild.id: current_ticket_counter}), you create a new int key in your dict, which doesn't override the str key that exists from loading the json file.
See this example:
import json
d = {1: 'a', '1': 'b'}
json.dumps(d)
>>> '{"1": "b", "1": "a"}'
The dict can hold both 1 and '1' as keys as they are different objects. But the json serialization will turn both into strings, as json uses strings as keys.
I supposed there is room for improvement in the json module as it doesn't seem to check that the stringified keys are all unique.
You can fix your code by making sure you use a string for the key in your dict:
ticket_counter_dict.update({str(reaction.message.guild.id): current_ticket_counter})

Using Python dict

I have the following Python dict. I'm trying to do a check with n if statement that payload contains "token"
{'payload': {'token': '3u4td7393493d9304'}, 'type': 'send'}
Below is the python code
if message['payload'] == 'token':
print("GOT IT");
print(message)
elif message['payload']['type'] == 'timedout':
print("TIMEDOUT!")
elif message['payload'] == 'locked':
print("LOCKED!")
done.set()
The current if statement for token is wrong. What is the proper way of checking if payload has "token" inside it?
To check whether a dictionary d contains key k, use k in d:
message = {'payload': {'token': '3u4td7393493d9304'}, 'type': 'send'}
# {'payload': {'locked': 'lockId'}, 'type': 'send'}
if 'token' in message['payload']:
print("GOT IT");
print(message)
print(f"token: {message['payload']['token']}")
elif message['type'] == 'timedout':
print("TIMEDOUT!")
elif 'locked' in message['payload']:
print("LOCKED!")
print(f"locked value: {message['payload']['locked']}")
# done.set()
Since you have nested dictionaries, message['payload'] is itself a dictionary, therefore to check whether it has key 'token', you have to use 'token' in message['payload'].
I've also added an example that demonstrates how to access the value that corresponds to the key 'token'.
Side note: this if-else does not seem to be exhaustive, and it lacks the default case. Maybe you should approach it a bit more systematically, and first make sure that you deal with every possible type of the message, and then for each type deal with each kind of payload.
The way i understand your question is you want to find whether or not 'token' exist in payload, regardless of the token value?
If yes, simple in array would suffice:
dc = {'payload': {'token': '3u4td7393493d9304'}, 'type': 'send'}
'token' in dc['payload'] # this would result in True
Just create a function which return True or False , now whenever you want to check pass value to that function and check :
def check_token(data_):
if 'token' in data_['payload']:
return True
else:
return False
Now back to your code , you can simply check by passing value to this function :
if check_token(data)==True:
print("GOT IT")
output:
GOT IT

boto3 TypeError: 'NoneType' object is not iterable

I'm trying to use boto3 to print the values of an EC2 tag I have called 'Function' but receive a TypeError: 'NoneType' object is not iterable error in line 7 after the code runs through about 20 objects. I've tried to catch this by checking if that value is None but still receive this error.
import boto3
s = boto3.Session(profile_name='default')
ec2 = s.resource('ec2')
for i in ec2.instances.all():
for tag in i.tags:
if tag['Value'] is None:
print("No Value")
else:
if tag['Key'] == 'Function':
print(tag['Value'])
You could try doing this and check:
def tag_to_dict(ec2):
tag_dict = {}
if ec2.tags is None:
return "No Value" ## Replace "No Value" with tag_dict to get an empty dict
for tag in ec2.tags:
tag_dict[tag['Key']] = tag['Value']
return tag_dict
You end up getting a dictionary with keys as keys and tag values as values.
Edit:
Try and see if you can get anything here:
for i in ec2.instances.all():
if i.tags is None:
continue
for tag in i.tags:
if tag['Key'] == 'Function':
print(tag['Value'])
It continues with the next iteration of the loop and ignores NoneType values.

Categories

Resources