List from configparser passing as argument to telethon errors - python

I got a little problem that make stuck me at code small script that collect data from telegram chats. For first i will show my code and config file:
Config.ini:
[account]
api_id = xxxx
api_hash = xxxx
[parser]
channels_to_parse = [-xxxx,-xxxx]
Run.py
import configparser
import asyncio
import time
from telethon import events
from telethon import TelegramClient
from telethon.tl import functions, types
from datetime import datetime
#load config file
config = configparser.ConfigParser()
config.read('config.ini', encoding="utf-8")
#telethon init
client = TelegramClient('sess', config.get("account", 'api_id'), config.get("account", 'api_hash'))
client.start()
#main cycle
#client.on(events.NewMessage(chats=config.get('parser' , 'channels_to_parse')))
async def main(event):
#some code...
client.run_until_disconnected()
The main problem goes from string that contains arguments for telethon that points chats IDs from which i collecting data:
ValueError: Cannot find any entity corresponding to "[-xxxx]"
When i passing arguments manually, without configparser:
#client.on(events.NewMessage(chats = [-xxxx, -xxxx]))
Everything works well. So i think that issue related to configparser or configparser parameters. I checked configparser docs and didn't find anything that can help me.
I already tried to use channels name instead IDs. Maybe who's can explain me what i do wrong.

I can't check this at the moment, but I have an idea that configparser returns the str type and you need a list. But I could be wrong(
UPDATE
I checked it out and I was right!
config.ini:
[parser]
channels_to_parse = -xxxx -xxxx
file.py:
parser = config.get('parser', 'channels_to_parse') # type str
chats = [int(i) for i in parser.split()] # type list
#client.on(events.NewMessage(chats=chats))

Related

Setting command parameter descriptions in discord.py

I am making a command in a bot to create a profile for a user. It is working fine, but I would like the description of the "name" parameter to say "What would you like to be called?".
Here is the code I currently have:
import discord
from discord import app_commands
#tree.command(name="makeprofile", description="Make your own profile!", guild=discord.Object(id=000000000000))
async def make_profile(interaction, preferred_name: str, pronouns: str):
db.insert({'id': interaction.user.id, 'name': preferred_name, 'pronouns': pronouns})
From the documentation:
#discord.app_commands.describe(**parameters)
Describes the given parameters by their name using the key of the keyword argument as the name.
So in your case:
#app_commands.describe(preferred_name = "What would you like to be called?")

Python flask server to retrieve certain records

I have this following python code for a Flask server. I am trying to have this part of the code list all my vehicles that match the horsepower that I put in through my browser. I want it to return all the car names that match the horsepower, but what I have doesn't seem to be working? It returns nothing. I know the issue is somewhere in the "for" statement, but I don't know how to fix it.
This is my first time doing something like this and I've been trying multiple things for hours. I can't figure it out. Could you please help?
from flask import Flask
from flask import request
import os, json
app = Flask(__name__, static_folder='flask')
#app.route('/HORSEPOWER')
def horsepower():
horsepower = request.args.get('horsepower')
message = "<h3>HORSEPOWER "+str(horsepower)+"</h3>"
path = os.getcwd() + "/data/vehicles.json"
with open(path) as f:
data = json.load(f)
for record in data:
horsepower=int(record["Horsepower"])
if horsepower == record:
car=record["Car"]
return message
The following example should meet your expectations.
from flask import Flask
from flask import request
import os, json
app = Flask(__name__)
#app.route('/horsepower')
def horsepower():
# The type of the URL parameters are automatically converted to integer.
horsepower = request.args.get('horsepower', type=int)
# Read the file which is located in the data folder relative to the
# application root directory.
path = os.path.join(app.root_path, 'data', 'vehicles.json')
with open(path) as f:
data = json.load(f)
# A list of names of the data sets is created,
# the performance of which corresponds to the parameter passed.
cars = [record['Car'] for record in data if horsepower == int(record["Horsepower"])]
# The result is then output separated by commas.
return f'''
<h3>HORSEPOWER {horsepower}</h3>
<p>{','.join(cars)}<p>
'''
There are many different ways of writing the loop. I used a short variant in the example. In more detail, you can use these as well.
cars = []
for record in data:
if horsepower == int(record['Horsepower']):
cars.append(record['Car'])
As a tip:
Pay attention to when you overwrite the value of a variable by using the same name.

Unexpected Error with FilteredElementCollector in pyrevit

Beginner in python, pyRevit, and Revit API so my apologies if I'm phrasing my question poorly. Today I used pyRevit to develop a simple pushbutton tool that worked, and then after a few minutes stopped working without anything being changed (that I'm aware of)
My tool adds all groups with excluded elements to the selection. It worked perfectly for a time, then started throwing this error, which I can't make heads or tails of:
Exception: The input argument "document" of function `anonymous-namespace'::FilteredElementCollector_constructor or one item in the collection is null at line 326 of file d:\ship\2018_px64\source\revit\revitdbapi\APIFilteredElementCollectorProxy.cpp. Parameter name: document
The path in the error message isn't one I recognize on my computer. Here's the relevant code (the traceback goes to line 24, which is "groups = FilteredElementCollector...":
from pyrevit import script
from pyrevit.framework import List
from pyrevit.framework import clr
from pyrevit import revit, DB
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
doc = DocumentManager.Instance.CurrentDBDocument
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
clr.ImportExtensions(Revit.GeometryConversion)
clr.AddReference("RevitAPI")
from Autodesk.Revit.DB import *
groups = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_IOSModelGroups).WhereElementIsNotElementType().ToElements()
selection = revit.get_selection()
SelectionIds = []
for group in groups:
name = group.Name
if "(members excluded)" in name:
SelectionIds.append(group.Id)
selection.set_to(SelectionIds)
Thanks a lot for any solutions, or even help deciphering the error message.

How to publish/subscribe a python “list of list” as topic in ROS

I am new to ROS and rospy, and I am not familiar with non-simple data type as topic.
I want to build a ROS node as both a subscriber and publisher: it receives a topic (a list of two float64), and uses a function (say my_function) which returns a list of lists of float64, then publish this list of list as a topic.
To do this, I built a node as following:
from pymongo import MongoClient
from myfile import my_function
import rospy
import numpy as np
pub = None
sub = None
def callback(req):
client = MongoClient()
db = client.block
lon = np.float64(req.b)
lat = np.float64(req.a)
point_list = my_function(lon, lat, db)
pub.publish(point_list)
def calculator():
global sub, pub
rospy.init_node('calculator', anonymous=True)
pub = rospy.Publisher('output_data', list)
# Listen
sub = rospy.Subscriber('input_data', list, callback)
print "Calculation finished. \n"
ros.spin()
if __name__ == '__main__':
try:
calculator()
except rospy.ROSInterruptException:
pass
I know clearly that list in Subscriber and Publisher is not a message data, but I cannot figure out how to fix it since it is not an integer nor list of integer.
This post on the ROS forums gives you most of what you need. This is also useful. You can define a new message type FloatList.msg with the following specification:
float64[] elements
And then a second message type FloatArray.msg defined as:
FloatList[] lists
Then your function could look like:
def callback(req):
client = MongoClient()
db = client.block
lon = np.float64(req.b)
lat = np.float64(req.a)
point_list = my_function(lon, lat, db)
float_array = FloatArray()
for i in range(len(point_list)):
float_list = FloatList()
float_list.elements = point_list[i]
float_array.lists[i] = float_list
pub.publish(float_array)
And then you can unpack it with:
def unpack_callback(float_array_msg):
for lst in float_array_msg.lists:
for e in lst.elements:
print "Here is an element: %f" % e
In general, it is recommended you put ROS related questions on the ROS Forums since you are way more likely to get an answer to your question there.
You can complicate yourself by defining a new ros Type in the msg OR use the default and easy to implement std_msgs Type, maybe will be useful to use a json module, so you serialize the data before publishing and deserialize it back on the other side after receiving...
the rest Pub/Sub , topic and handlers remain the same :)
I agree with the solution, I thought about organizing it a bit more
Create a file FloatArray.msg in your catkin_ws in the src folder where you have all your other message files.
Build your env using catkin_make or catkin build.
In your script (e.g. Python script) import the message type and use it in the subscriber e.g.
joint_state_publisher_Unity = rospy.Publisher("/joint_state_unity", FloatArray , queue_size = 10)
specific case (bonus :)): if you are using Unity and ROS# build the message in Unity

Using ExtractMsg in a loop?

I am trying to write a script that will extract details from Outlook .msg files and append then to a .csv file. ExtractMsg (https://github.com/mattgwwalker/msg-extractor) will process the messages one at a time, at the command line with 'python ExtractMsg.py message' but I can't work out how to use this to loop through all the messages in the directory.
I have tried:
import ExtractMsg
import glob
for message in glob.glob('*.msg'):
print 'Reading', message
ExtractMsg(message)
This gives "'module' object is not callable". I have tried to look at the ExtractMsg module but the structure of it is beyond me at the moment. How can I make the module callable?
ExtractMsg(message)
You are trying to call module object - exactly what error message us telling you.
Perhaps you need to use ExtractMsg.Message class instead
msg = ExtractMsg.Message(message)
In the next link on the very bottom you will find example of usage
https://github.com/mattgwwalker/msg-extractor/blob/master/ExtractMsg.py
Thanks all - the following sorted it:
import ExtractMsg
import glob
for message in glob.glob('*.msg'):
print 'Reading', message
msg = ExtractMsg.Message(message)
body = msg._getStringStream('__substg1.0_1000')
sender = msg._getStringStream('__substg1.0_0C1F')

Categories

Resources