Trouble importing filters using Pyrogram - python

I am facing this error and I do not know how to solve it and I think I have written my code correctly
File "C:\Users\Revenger\index.py", line 1, in <module>
from pyrogram import Client, Filters
ImportError: cannot import name 'Filters' from 'pyrogram' (C:\Users\Revenger\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pyrogram\__init__.py)
This is my Code
from pyrogram import Client, filters
from pyrogram.methods.chats.get_chat_members import Filters
app = Client("Client", bot_token="Token")
#app.on_message(Filters.private & Filters.command('start'))
def startmsg(client, message):
message.reply("Hi Wassimo Bot is Here")
app.run() #"long-polling"

use filters instead of Filters
from pyrogram import filters, Client
delete second line , becouse you are importing Filters from random place

import methods relative to version
in old versions:
from pyrogram import Filters
from pyrogram.types import InlineKeyboardMarkup # Example
in newer version:
from pyrogram import filters
from pyrogram import InlineKeyboardMarkup # Example

Related

trouble importing enums from google.cloud.speech_v1

I have this code:
from google.cloud import speech_v1
from google.cloud.speech_v1 import enums
import os
import importlib
# Import the enums module from the google.cloud.speech_v1 package
enums = importlib.import_module("google.cloud.speech_v1.enums")
# Set your Google Cloud project and service account credentials
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "creds.json"
# Create a client for the Google Cloud Speech-to-Text API
stt_client = speech_v1.SpeechClient()
# Transcribe the audio data
response = stt_client.recognize(
audio=speech_v1.types.RecognitionAudio(uri="gs://focus-0/speech-to-text-sample.wav"),
config=speech_v1.types.RecognitionConfig(
encoding=enums.RecognitionConfig.AudioEncoding.FLAC,
sample_rate_hertz=48000,
language_code="en-US"
)
)
# Print the transcribed text
for result in response.results:
print("Transcription: {}".format(result.alternatives[0].transcript))
When I run it, I get this:
Traceback (most recent call last):
File "/Users/dir/git/fp-scrapers/speech/1-STT.py", line 5, in <module>
from google.cloud.speech_v1 import enums
ImportError: cannot import name 'enums' from 'google.cloud.speech_v1' (/opt/homebrew/lib/python3.9/site-packages/google/cloud/speech_v1/__init__.py)
I have tried several ways to import enums, but none of them have worked.
Does anyone see what I'm doing wrong?
enums and types have been removed in the 2.x versions of the library
Mentioned in this github.Refer to this migration guide. You can refer to this quick start for setup instructions and an updated client library
Before:
from google.cloud import speech
encoding = speech.enums.RecognitionConfig.AudioEncoding.LINEAR16
audio = speech.types.RecognitionAudio(content=content)
After:
from google.cloud import speech
encoding = speech.RecognitionConfig.AudioEncoding.LINEAR16
audio = speech.RecognitionAudio(content=content)

Trying to reuse code across multiple Flask servers, stuck on importing with errors "ModuleNotFoundError" or "ImportError"

My goal is to import code into three separate Flask servers. It's not going well. I am on python 3.10.4. I have read perhaps 10 different posts that say things like "put a __init__.py file in your folders" which I have done.
For context I'm not exactly new to Python but I've never learned the importing/module system properly.
I have three Flask servers that run scraping operations on different (but similar) websites. I need them to be separate for various reasons. Anyway, all three need to run the same procedure of getting an IP for a proxy from my proxy provider. For this I have some code:
# we don't need the details here so I snip it to save space
def get_proxy_ip(choice):
r = requests.get(download_list, headers={"Authorization": "Token " + token})
selected_proxy_ip = r.json()["results"][choice]["proxy_address"]
selected_proxy_port = r.json()["results"][choice]["port"]
print(selected_proxy_ip)
return selected_proxy_ip, selected_proxy_port
I want to use this function across all 3 of my Flask servers. Here are some various ways I've tried to import the code into one of the Flask servers:
scrapers/rentCanada/app.py
import requests
from flask import Flask, request, make_response
print("cats")
app = Flask(__name__)
print(__name__, __package__)
# from ..shared.ipgetter import get_proxy_ip
# from ..shared.checker import check_public_ip
# from scrapers.shared.ipgetter import get_proxy_ip
# from scrapers.shared.checker import check_public_ip
import shared.ipgetter as ipgetter
import shared.checker as checker
None of them work.
import shared.ipgetter as ipgetter yields:
cats
__main__ None
Traceback (most recent call last):
File "/home/rlm/Code/canadaAps/scrapers/rentCanada/app.py", line 10, in <module>
import shared.ipgetter as ipgetter
ModuleNotFoundError: No module named 'shared'
ModuleNotFoundError: No module named 'scrapers' yields: ModuleNotFoundError: No module named 'scrapers'
from ..shared.ipgetter import get_proxy_ip yields: ImportError: attempted relative import with no known parent package
At this point you need to see my folder structure.
/scrapers
..__init__.py
..setup.py
../rentCanada
.....__init__.py
.....app.py
../rentFaster
.....__init__.py
.....app.py
../rentSeeker
.....__init__.py
.....app.py
../shared
.....__init__.py
.....ipgetter.py
.....checker.py
I need to be able to use any of the app.py files as entry points.
I also tried setup.py with this:
from setuptools import setup, find_packages
setup(
name = 'tools',
packages = find_packages(),
)
followed by python setup.py install but that didn't make a "tools" import available in app.py like I wanted.
As a final note I suspect someone will tell me to use a blueprint. To me those look like a tool I'd use if I was adding a route. I'm not sure they're right for a simple function, but maybe I'm wrong.
My solution for now is to run Flask with python rentCanada/app.py from the /scrapers folder and use this code
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent)) # necessary so util folder is available
import requests
from flask import Flask, request, make_response
print("cats")
app = Flask(__name__)
print(__name__, __package__)
from util.ipgetter import get_proxy_ip
from util.checker import check_public_ip
So the program appends the app.py file folder's parent folder to the path. That makes the util folder (which used to be shared but had a naming conflict) available within the app.py file.

Discord.py random syntax error when loading bot.run

I was following a tutorial to learn some new discord.py techniques but when following a tutorial I came across this error which I can't fix, this is the code:
import discord
import asyncio
from discord.ext import commands
import os
from discord.utils import get
from dotenv import load_dotenv
load_dotenv()
DISCORD_TOKEN = os.getenv("Nzg4NjQxMTQzNDExNTcyNzk2.X9mdTA.3NrZ87u3cn8-i5icp7AQD1xdmbQ")
bot = commands.Bot(command_prefix="/"
bot.run('Nzg4NjQxMTQzNDExNTcyNzk2.X9mdTA.3NrZ87u3cn8-i5icp7AQD1xdmbQ')
My problem is that when I run the code I get a syntax error specifically on the "b" at the beginning of bot.run() any help is appreciated.
If your code is exactly what you've posted, you're just missing a ) at the line before the last.
bot = commands.Bot(command_prefix="/" # <-- MISSING PARENTHESIS HERE
bot.run('Nzg4NjQxMTQzNDExNTcyNzk2.X9mdTA.3NrZ87u3cn8-i5icp7AQD1xdmbQ')
In cases like this Python throws an error at the line below because it can't understand the previous line has ended.

I cannot import a module and I don't know why Python: ImportError: Cannot import name X

I'm having the following error when I try to run a Flask app:
File "/home/patterson/Documentos/CPFL/cpfl/computer.py", line 12, in <module>
from cpfl.cpfl import sendmail
ImportError: cannot import name 'sendmail'
sendmail is a function I'm trying to import from the cpfl.py module which is a flask app.
cpfl.py:
...
app = Flask(__name__)
...
The structure of my project is as follows:
I have no idea why import does not work.
Could someone help-me?
Have you tried import cpfl and then when you call the method you use cpfl.sendmail?

"ImportError: cannot import name mail" in Flask

I have built is a simple web app with Flask and Python, which I intend to upload to Heroku.
When starting my app locally, with the following script:
#!venv/bin/python
from app import app
app.run(debug = True)
I get this error message:
Traceback (most recent call last):
File "./run.py", line 2, in <module>
from app import app, mail
File "/home/ricardo/personalSite/app/__init__.py", line 3, in <module>
from app import index
File "/home/ricardo/personalSite/app/index.py", line 6, in <module>
from emails import send_email
File "/home/ricardo/personalSite/app/emails.py", line 2, in <module>
from app import app, mail
ImportError: cannot import name mail
So, it cannot import mail.
Inside the app directory I have this __init__.py, here is were I create the Mail object that is ginving me trouble to import:
from flask import Flask
app = Flask(__name__)
from app import index
from flask.ext.mail import Mail
mail = Mail(app)
And this is the file emails.py where I call the send_mail function:
from flask.ext.mail import Message
from app import app, mail
from flask import render_template
from config import ADMINS
from decorators import async
So, according to the error message, the error is in this file, in the from app import app, mail.
What is the problem? Why can't it import mail?
Update:
This is my directory listing:
persSite\
venv\
<virtual environment files>
app\
static\
templates\
__init__.py
index.py
emails.py
decorators.oy
tmp\
run.py
You have a circular dependency. You have to realize what Python is doing when it imports a file.
Whenever Python imports a file, Python looks to see if the file has already started being imported before. Thus, if module A imports module B which imports module A, then Python will do the following:
Start running module A.
When module A tries to import module B, temporarily stop running module A, and start running module B.
When module B then tries to import module A, then Python will NOT continue running module A to completion; instead, module B will only be able to import from module A the attributes that were already defined there before module B started running.
Here is app/__init__.py, which is the first file to be imported.
from flask import Flask
app = Flask(__name__)
from app import index # <-- See note below.
from flask.ext.mail import Mail
mail = Mail(app)
When this file is imported, it is just Python running the script. Any global attribute created becomes part of the attributes of the module. So, by the time you hit the third line, the attributes 'Flask' and 'app' have been defined. However, when you hit the third line, Python begins trying to import index from app. So, it starts running the app/index.py file.
This, of course, looks like the following:
from flask.ext.mail import Message
from app import app, mail # <-- Error here
from flask import render_template
from config import ADMINS
from decorators import async
Remember, when this Python file is being imported, you have thus far only defined Flask and app in the app module. Therefore, trying to import mail will not work.
So, you need to rearrange your code so that if app.index relies on an attribute in app, that app defines that attribute before attempting to import app.index.
This is probably the problem:
from app import app, mail
In the file 'app/emails.py' the import is from the current module, not a nested app module. Try:
from . import app, mail
If it doesn't work, you should update your question with a more detailed directory listing.

Categories

Resources