Friday, March 11, 2022

Telegram - Import Members into a Channel

There are two conditions to Import / Export members of a telegram channel.

1) You should be an administrator or owner of the channel, then only you will be able to import or export members.

2) If a member has selected ‘My Contacts’ option in ‘who can add you to groups and channels’ then you should be added in his/her contact list only then you can import him/her in the channel.

To import channel members, First Generate api id and api hash in your telegram account. To do this, open my.telegram.org
Login using your registered phone number.
Now Open Link Development Tools and copy your api id and hash
We will use the api id and hash in the Python Script

 Create virtual environment with python 3 and install Telethon using pip.

virtualenv telegram -p /usr/bin/python3
source telegram/bin/activate
pip install Telethon==1.23.0
Update API ID, API hash, telegram registered phone number and channel username(it can be found on the channel description page) in the following python script import.py.

from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser
from telethon.errors.rpcerrorlist import PeerFloodError, UserPrivacyRestrictedError
from telethon.tl.functions.channels import InviteToChannelRequest
import sys
import csv
import traceback
import time

api_id = 9999999
api_hash = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'

client = TelegramClient('session_name', api_id, api_hash)
client.start()

channel = client.get_entity('pythonlovers07')
print(channel)

input_file = 'members.csv'
users = []
with open(input_file, encoding='UTF-8') as f:
    rows = csv.reader(f,delimiter=",",lineterminator="\n")
    next(rows, None)
    for row in rows:
        user = {}
        user['username'] = row[0]
        user['id'] = int(row[1])
        user['access_hash'] = int(row[2])
        user['name'] = row[3]
        users.append(user)
        
 
mode = int(input("Enter 1 to add by username or 2 to add by ID: "))

for user in users:
    try:
        print ("Adding {}".format(user['id']))
        if mode == 1:
            if user['username'] == "":
                continue
            user_to_add = client.get_input_entity(user['username'])
            print(user['username'])
        elif mode == 2:
            user_to_add = InputPeerUser(user['id'], user['access_hash'])
        else:
            sys.exit("Invalid Mode Selected. Please Try Again.")
        target_group = 'pythonlovers07'
        target_group_entity = InputPeerChannel(channel.id,channel.access_hash)
        print(target_group_entity)
        print(user_to_add)               
        client(InviteToChannelRequest(target_group_entity,[user_to_add]))
        print("Waiting 60 Seconds...")
        time.sleep(60)
    except PeerFloodError:
        print("Getting Flood Error from telegram. Script is stopping now. Please try again after some time.")
    except UserPrivacyRestrictedError:
        print("The user's privacy settings do not allow you to do this. Skipping.")
    except:
        traceback.print_exc()
        print("Unexpected Error")
        continue
Run the Python script in the same virtual env.

python import.py

members.csv should be in same directory where you are running the script. members.csv has all the exported channel members. 

It will list all your channels. Choose number of the channel into you want to import members. Members will be imported in the channel.

To see the steps :

 



If you want to export telegram channel members, check other post of the blog.

https://linuxamination.blogspot.com/2022/04/telegram-export-members-of-channel.html






       

Thursday, March 3, 2022

Themosis Framework - Laravel based wordpress setup on localhost

1) Download existing code and database and put code into htdocs and import sql file or if it is new setup, follow this url.

https://framework.themosis.com/docs/2.0/installation/

2) If wp_options has different domain on production, Use same domain in virtualhost for local setup. 

3) Point the domain upto htdocs (folder inside project root dir) and open it in browser.

4) If you get error

Unable to define the environment. / Unable to locate your environment configuration file. / Missing environment variables. / Error establishing a database connection
Solution :
Add your server's hostname in xyz.com/config/environment.php as a production value. In my case it is localserver.
<?php
return array(

    'local'         => ['xyz.local', 'xyz2.local'],
    'staging'       => 'dev.xyz.co.uk',
    'production'    => ['ip-172-16-150-95.eu-west-1.compute.internal', 'ip-172-31-13-11.eu-west-1.compute.internal', 'localserver']
);

5) Now if you get db connection error 'Error establishing a database connection'
Put correct database credentials and correct urls in xyz.com/.env.production.php
<?php
return [
    'DB_NAME'                       => 'xyz',
    'DB_USER'                       => 'admin',
    'DB_PASSWORD'                   => 'password',
    'DB_HOST'                       => 'localhost',
    'WP_HOME'                       => 'http://xyz.com',
    'WP_SITEURL'                    => 'http://
xyz.com/cms',
    'DEV_EMAIL'                     => 'developer@xyz.co.uk',
    'DEV_NAME'                      => '
developer',
]

6) If errors are resolved but it opens blank page in place of site, change owner of complete project to apache or www-data depends on it is centos or ubuntu.
sudo chown -R apache:apache xyz.com
It is not able to create files in xyz.com/storage/views, that's why you are getting blank page once necessary files are created, site can be opened.

7) After doing all above things but still you get 'Error establishing a database connection'. Check if you have created wp-config.php inside cms folder.
This creation is the reason of database connection error. There should be only one wp-config.php and it is in xyz.com/htdocs/wp-config.php
wp-admin Details :

http://xyz.co.in/cms/wp-login.php
Username - admin
Password - xxxxxxxxxxxxx
8) Fix issue 'Error establishing a database connection' in existing setup.
cd xyz.com          
nano config/environment.php
Remove same domain from staging and production.
nano .env.production.php
Make credentials and DB Variable correct.
rm htdocs/cms/wp-config.php
nano config/environment.php  
chown -R apache:apache storage/views/

Configure SNS service on AWS

To send sms in india, sns service should be configured in Singapore. Mumbai is not providing facility right now. 

To send sms in US, service should be configured in US region.

1) Open SNS in AWS Management Console.  

Create Topic (Topic name + Display name > create topic)

2) Create Subscription (ARN : Created Topic Name + Protocol : Email > Create subscription)

3) Create user in IAM and attach policy SNS full access.

4) Now try sending sms using python script 

pip3 install boto3

nano sms.py

    import boto3
    # Create an SNS client
    access_key = 'ACLAXXXXXXXXXXXXXZBA'
    secret = 'Zwxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    region = "ap-southeast-1"
    number = '+9199xxxxxxxx'
    sender_id = 'senderidname'
    sms_message = 'Your code: 123456'
    sns = boto3.client('sns', aws_access_key_id=access_key, aws_secret_access_key=secret, region_name=region)
    sns.publish(PhoneNumber=number, Message=sms_message, MessageAttributes={'AWS.SNS.SMS.SenderID': {'DataType': 'String', 'StringValue':     sender_id}, 'AWS.SNS.SMS.SMSType': {'DataType': 'String', 'StringValue': 'Transactional'}})
python sms.py 

5) If you do not receive sms then check error in cloudwatch but before it you need to enable the logs.
Click on Text Messaging (SMS) option > Text messaging preferences > Edit
Delivery status logging - optional > Create new service role

It will take you on IAM page and it will create roles for
SNS Success feedback and SNS Failure feedback > Allow

Once roles are created

Delivery status logging - optional > Use existing service role > add ARN of failure feedback
arn:aws:iam::360209543005:role/SNSFailureFeedback > save changes

Now errors will be reported in cloudwatch log group
check the error > cloudwatch > Log groups

 "delivery":
        "phoneCarrier": "Vodaphone - Kerela",
        "mnc": 90,
        "numberOfMessageParts": 1,
        "destination": "+9199xxxxxxxx",
        "priceInUSD": 0.00223,
        "smsType": "Promotional",
        "mcc": 404,
        "providerResponse": "Phone carrier has blocked this message",
        "dwellTimeMs": 172,
        "dwellTimeMsUntilDeviceAck": 669
    },
    "status": "FAILURE"
Phone carrier has blocked the sms that's why it is not delivered because you were sending promotional sms type.
You should have sent Transaction sms type.
Either select default sms type transactional
Click on Text Messaging (SMS) option > Text messaging preferences > Edit > Default message type > transactional
OR send message type in the code, just like above example did. Now message will be delivered.

Send message by sender ID
i) US does not support sender ID
ii) To send message in India by sender id
Generate request in support for sender ID.
https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-awssupport-sender-id.html