def __init__(self): self.config = Config.get_conf(self, identifier=209348585) with open('cogs/coc/apikey.json', 'r') as f: res = json.loads(f.read()) client = coc.login(str(res['user']),str(res['pass']),client=coc.EventsClient) default_global = {"userid": ""} self.config.register_global(**default_global) self.config.register_user( username=None )
coc_pass = settings['supercell']['pass2'] else: token = settings['discord']['test_token'] prefix = ">" log_level = "DEBUG" coc_names = "dev" coc_email = settings['supercell']['user2'] coc_pass = settings['supercell']['pass2'] description = """Welcome to The Arborist - by TubaKid All commands must begin with a slash""" coc_client = coc.login(coc_email, coc_pass, client=coc.EventsClient, key_names=coc_names, key_count=2, correct_tags=True) links_client = discordlinks.login(settings['links']['user'], settings['links']['pass']) intents = discord.Intents.default() intents.members = True class OakBot(commands.Bot): def __init__(self): super().__init__( command_prefix=prefix, description=description,
import coc with open("credentials.txt") as file: adatok = file.readlines() cred = [x.strip() for x in adatok] if len(cred) < 2: print("Nem adtad meg a belépési adatokat") if len(cred) == 2 : print("Nem adtál meg kereséshez szükséges adatokat") print() client = coc.login(cred[0], cred[1]) player_tag = cred[2] clan_tag = cred[3] async def main(): # Ha van megadva player tag if player_tag: player = await client.get_player(player_tag) print("Játékos neve: " + str(player)) player_clan = await player.get_detailed_clan() print("Játékos klánja: " + str(player_clan)) print("A játékos hősei: ") for hero in player.heroes: print("{}: Lv {}/{}\n".format(str(hero), hero.level, hero.max_level)) print()
Store authentication info in separate file: line 1: CoC dev username line 2: CoC dev password line 3: DC info channel ID line 4: DC bot OAUTH2 token line 5: Your clan's tag ''' with open("../orabot_food.txt") as f: auth = f.readlines() auth = [x.strip() for x in auth] clan_tag = auth[4] # Tag of the clan that you want to follow. coc_client = coc.login( auth[0], auth[1], key_count=5, key_names="Bot key", client=coc.EventsClient, ) bot = commands.Bot(command_prefix="!") INFO_CHANNEL_ID = int( auth[2]) # ID of the info channel where the bot will post messages. @coc_client.event async def on_clan_member_versus_trophies_change(old_trophies, new_trophies, player): await bot.get_channel(INFO_CHANNEL_ID).send( "{0.name}-nek jelenleg {1} versus trófeája van".format( player, new_trophies))
import coc import asyncio loop = asyncio.get_event_loop() client = coc.login('*****@*****.**', 'xUjpuw-jyrxe5-mydjum') print(dir(client)) player = loop.run_until_complete(client.get_player('#QULC2GV9')) season_list = loop.run_until_complete(client.get_seasons(player.league.id)) #player2 = loop.run_until_complete(client.get_player('#9P9PRYQJ')) print(season_list[-1]['id']) print(player.league.id) # List of locations await client.search_locations() # List of leagues await client.search_leagues() # Clash of stats # https://www.clashofstats.com/players/jaguar__-Y9J80QRC/achievements # List of leagues # await client.get_location_players() # await client.get_location_clan() # load = await client.get_season_rankings('29000022', '2019-11') # legend = loop.run_until_complete(load) # print(legend) #legend = loop.run_until_complete(client.get_season_rankings(player.league.id, '2019-11')) #print(legend) ##9P9PRYQJ sgtmajordoobie-9P9PRYQJ client.close()
# Import other libraries to be used in your code import coc import traceback import creds from discord.ext import commands description = "This is for my FWA clan" # This is where you can select the prefix you'd like used for your bot commands prefix = "!" # Here you make the connection to the COC API using the coc.py library coc_client = coc.login(creds.coc_dev_email, creds.coc_dev_password, client=coc.EventsClient, key_names="FWA") # These are the cogs that you are using in your bot initial_extensions = ("cogs.general", ) class fwautils(commands.Bot): # The __init__ method is a standard method seen at the beginning of most classes # it declares the variables that will be used throughout the class def __init__(self): super().__init__(command_prefix=prefix, description=description, case_insensitive=True) self.coc = coc_client
import coc import asyncio import logging logging.basicConfig(level=logging.DEBUG) # email and password is your login credentials used at https://developer.clashofclans.com coc_client = coc.login(email="*****@*****.**", password="******") async def get_warlog_for_clans(clan_tags: list): war_logs = {} for tag in clan_tags: # if we're not allowed to view warlog (private in game), this will raise an exception try: warlog = await coc_client.get_warlog(tag) except coc.PrivateWarLog: warlog = [] war_logs[tag] = warlog # return a dict of list of war logs: {'tag': [list_of_warlog_objects]} return war_logs async def get_clan_tags_names(name: str, limit: int): clans = await coc_client.search_clans(name=name, limit=limit) # return a list of tuples of name/tag pair ie. [(name, tag), (another name, another tag)] return [(n.name, n.tag) for n in clans]
import traceback import json import time import discord from riotwatcher import LolWatcher from discord.ext import commands with open("pythonappbot_food.txt") as f: auth = f.readlines() auth = [x.strip() for x in auth] coc_client = coc.login( auth[2], auth[3], key_count=1, key_names="discord_bot_key", client=coc.EventsClient, ) clan_tag = auth[4] bot = commands.Bot(command_prefix="!") CHANNEL_ID = int(auth[1]) @coc_client.event async def on_clan_member_versus_trophies_change(old_trophies, new_trophies, player): await bot.get_channel(CHANNEL_ID).send( "{0.name}-nek jelenleg {1} versus trófeája van.".format( player, new_trophies))
try: pool = loop.run_until_complete( asyncpg.create_pool(keys.postgres, command_timeout=60)) bot = FroschBot(bot_config=keys.bot_config(bot_mode), keys=keys, bot_mode=bot_mode, coc=coc, pool=pool) bot.run() except Exception as error: exc = ''.join( traceback.format_exception(type(error), error, error.__traceback__, chain=True)) print(exc) log.error(exc) if __name__ == '__main__': coc_client = coc.login(keys.coc_api['email'], keys.coc_api['password'], throttle_limit=30, key_count=3) args = BotArgs().parse_the_args() if args.live_mode: main('live_mode', coc_client) else: main('dev_mode', coc_client)
prefix = ">" log_level = "DEBUG" coc_names = "dev" else: token = settings['discord']['test_token'] prefix = ">" log_level = "DEBUG" coc_names = "delete_me" description = ("Welcome to the Clash API Developers bot. This is a custom bot created by and for the users of the " "Clash API Developers Discord server. If you have questions, please reach out to " "@Admins on this server.") coc_client = coc.login(settings['supercell']['user'], settings['supercell']['pass'], client=coc.EventsClient, key_names=coc_names, key_count=2, correct_tags=True) intents = discord.Intents.default() intents.members = True intents.presences = True class ApiBot(commands.Bot): def __init__(self): super().__init__(command_prefix=prefix, description=description, case_insensitive=True, intents=intents, )
# this example assumes you have discord.py > v1.0.0 # installed via `python -m pip install -U discord.py` # for more info on using discord.py, see the docs at: # https://discordpy.readthedocs.io/en/latest import discord from discord.ext import commands import coc import traceback bot = commands.Bot(command_prefix="?") coc_client = coc.login( "email", "password", key_count=5, key_names="My funky name!", client=coc.EventsClient, ) INFO_CHANNEL_ID = 123456678 # some discord channel ID @coc_client.event async def on_clan_member_join(member, clan): await bot.get_channel(INFO_CHANNEL_ID).send("{0.name} ({0.tag}) just " "joined our clan {1.name} " "({1.tag})!".format( member, clan)) @coc_client.event async def on_player_name_change(old_name, new_name, player):
import coc client = coc.login("email", "pass", client=coc.EventsClient) @client.event async def on_clan_member_join(member, clan): print("{} just joined our clan {}!".format(member.name, clan.name)) @client.event async def on_clan_member_leave(member, clan): print("Oh no! {} just left our clan {}!".format(member.name, clan.name)) @client.event async def on_war_attack(attack, war): print("{} just attacked {} for {} stars! It was a {} war.".format( attack.attacker.name, attack.defedender.name, attack.stars, war.type)) tags = ["#tag", "#tag2", "#tag3"] client.add_clan_update(tags, retry_interval=30) client.add_war_update(tags, retry_interval=300) client.run_forever()
)) command_prefix = None key_names = 'test' elif beta: command_prefix = '//' key_names = 'test' creds.bot_token = creds.beta_bot_token else: command_prefix = '//' key_names = 'windows' coc_client = coc.login( creds.email, creds.password, client=coc.EventsClient, key_names=key_names, throttle_limit=30, key_count=1, key_scopes=creds.scopes, throttler=coc.BatchThrottler, ) links_client = discordlinks.login(creds.links_username, creds.links_password) description = "A simple discord bot to track donations of clan families in clash of clans." intents = discord.Intents.none() intents.guilds = True intents.guild_messages = True intents.guild_reactions = True intents.members = True intents.emojis = True log = logging.getLogger()
import discord import coc import traceback from discord.ext import commands with open("dapi.txt") as f: auth = f.readlines() auth = [x.strip() for x in auth] clan_tag = auth[4] coc_client = coc.login( email=auth[2], password=auth[3], key_count=5, key_names="Bot key", client=coc.EventsClient, ) bot = commands.Bot(command_prefix="!") CHANNEL_ID = int(auth[1]) @coc_client.event async def on_clan_member_versus_trophies_change(old_trophies, new_trophies, player): await bot.get_channel(CHANNEL_ID).send( "{0.name}-nek jelenleg {1} versus trófeája van".format( player, new_trophies))
# Import other libraries to be used in your code import coc import traceback import creds from database.database import Bot_Database from discord.ext import commands description = "This is where you provide a concise description of your bot. Not sure if this is ever visible anywhere." # This is where you can select the prefix you'd like used for your bot commands prefix = "!" # Here you make the connection to the COC API using the coc.py library coc_client = coc.login(creds.coc_dev_email, creds.coc_dev_password, client=coc.EventsClient) # These are the cogs that you are using in your bot initial_extensions = ( "cogs.general", "cogs.special", "cogs.database_bg", "cogs.war-reporter", ) # File path to your sqlite3 db file SQLITE_FILE = 'database/bot_database.db' class MyBot(commands.Bot): # The __init__ method is a standard method seen at the beginning of most classes # it declares the variables that will be used throughout the class
initial_extensions = [ "cogs.newhelp", "cogs.owner", "cogs.pull", ] if __name__ == "__main__": bot.remove_command("help") bot.repo = git.Repo(os.getcwd()) bot.db = LegendDB(bot) loop = asyncio.get_event_loop() pool = loop.run_until_complete(bot.db.create_pool()) bot.loop = loop bot.db.pool = pool bot.logger = logger bot.coc_client = coc.login(settings['supercell']['user'], settings['supercell']['pass'], key_names=coc_names) for extension in initial_extensions: try: bot.load_extension(extension) logger.debug(f"{extension} loaded successfully") except Exception as e: logger.info(f"Failed to load extension {extension}") traceback.print_exc() bot.run(token)
import asyncio import coc client = coc.login('email', 'pass', client=coc.EventsClient) @client.event async def on_clan_member_join(member, clan): print('{} just joined our clan {}!'.format(member.name, clan.name)) async def on_clan_member_leave(member, clan): print('Oh no! {} just left our clan {}!'.format(member.name, clan.name)) async def when_someone_attacks(attack, war): print('{} just attacked {} for {} stars! It was a {} war.'.format( attack.attacker.name, attack.defedender.name, attack.stars, war.type)) client.add_events(on_clan_member_join, function_dicts={'on_war_attack': when_someone_attacks}) client.add_clan_update('tag', 'another tag', retry_interval=30) client.add_war_update('clan tag', retry_interval=60) client.start_updates('all') client.run_forever()
# this example assumes you have discord.py > v1.0.0 # installed via `python -m pip install -U discord.py` # for more info on using discord.py, see the docs at: # https://discordpy.readthedocs.io/en/latest import discord from discord.ext import commands import coc import traceback bot = commands.Bot(command_prefix='?') coc_client = coc.login('email', 'password', key_count=5, key_names='My funky name!', client=coc.EventsClient) INFO_CHANNEL_ID = 123456678 # some discord channel ID @coc_client.event async def on_clan_member_join(member, clan): await bot.get_channel(INFO_CHANNEL_ID).send('{0.name} ({0.tag}) just ' 'joined our clan {1.name} ' '({1.tag})!'.format( member, clan)) @coc_client.event async def on_player_name_change(old_name, new_name, player): await bot.get_channel(INFO_CHANNEL_ID).send( 'Name Change! {0} is now called {1} '
import os import traceback import coc import discord from coc import utils from discord.ext import commands INFO_CHANNEL_ID = 761848043242127370 # some discord channel ID clan_tags = ["#20090C9PR", "#202GG92Q", "#20C8G0RPL"] bot = commands.Bot(command_prefix="?", intents=discord.Intents.all()) coc_client = coc.login( os.environ["DEV_SITE_EMAIL"], os.environ["DEV_SITE_PASSWORD"], key_names="coc.py tests", client=coc.EventsClient, ) logging.basicConfig(level=logging.ERROR) @bot.event async def on_ready(): print("Logged in!!") @coc_client.event @coc.ClanEvents.member_join(tags=clan_tags) async def on_clan_member_join(member, clan): await bot.get_channel(INFO_CHANNEL_ID).send( "{0.name} ({0.tag}) just "
import logging, actions, buttons, clash, coc, os from user import User API_EMAIL = os.environ["API_EMAIL"] API_PASSWORD = os.environ["API_PASSWORD"] LA_TAG = os.environ["LA_TAG"] client = coc.login(API_EMAIL, API_PASSWORD) # Enable logging logging.basicConfig(format='%(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__ + ".py") def start(update, context) -> None: data = update.effective_user user = User(data.first_name, data.last_name, data.username) logger.info(user.log("ha iniciado el bot.")) actions.escribiendo(update.message.chat) update.message.reply_text( text=f"¡Bienvenido <b>{user.get_name()}!</b>" + actions.START, parse_mode="HTML" ) def list_commands(update, context) -> None: data = update.effective_user user = User(data.first_name, data.last_name, data.username) logger.info(user.log("solicitó los comandos.")) actions.escribiendo(update.message.chat) update.message.reply_text( text=actions.COMMANDS, parse_mode="HTML"
def load_coc_client(): global coc_client coc_client = coc.login(os.getenv('EMAIL'), os.getenv('PASS'), key_names="Made with coc.py", client=coc.EventsClient)
import discord import coc import traceback from discord.ext import commands from pyjavaproperties import Properties bot = commands.Bot(command_prefix="!") p = Properties() p.load(open('bot.properties')) #coc_client = coc.login(p['coc_email'], p['coc_pass'], key_count=5, key_names="Bot key", client=coc.EventsClient) coc_client = coc.login(p['coc_email'], p['coc_pass'], key_count=5, key_names="Bot key", client=coc.EventsClient) @bot.command() async def hello(ctx): await ctx.send("Hello!") @bot.command() async def heroes(ctx, player_tag): print("Used player_tag: {}".format(player_tag)) player = await coc_client.get_player(str(player_tag)) print("Player's name: {}".format(player.name)) to_send = "" for hero in player.heroes: to_send += "{}: Level {}/{}\n".format(str(hero), hero.level, hero.max_level) try: await ctx.send(to_send) except:
token = settings['discord']['testToken'] prefix = ">" log_level = "DEBUG" coc_names = "dev" description = """Discord bot used to track Clash of Clans Trophy Push Events - by TubaKid/wpmjones""" initial_extensions = [ "cogs.admin", "cogs.newhelp", "cogs.events", ] coc_client = coc.login(settings['supercell']['user'], settings['supercell']['pass'], client=coc.EventsClient, key_names=coc_names, throttle_limit=40) class PushBot(commands.Bot): def __init__(self): super().__init__(command_prefix=prefix, description=description, case_insensitive=True, fetch_offline_members=True) self.remove_command("help") self.token = settings['discord']['testToken'] self.session = aiohttp.ClientSession(loop=self.loop) self.coc = coc_client self.color = discord.Color.purple()
import coc import asyncio import logging log = logging.getLogger('coc') log.setLevel(logging.DEBUG) # email and password is your login credentials used at https://developer.clashofclans.com coc_client = coc.login(email='email', password='******', key_count=5) async def get_warlog_for_clans(clan_tags: list): war_logs = {} for tag in clan_tags: # if we're not allowed to view warlog (private in game), this will raise an exception try: warlog = await coc_client.get_warlog(tag) except coc.PrivateWarLog: warlog = [] war_logs[tag] = warlog # return a dict of list of war logs: {'tag': [list_of_warlog_objects]} return war_logs async def get_clan_tags_names(name: str, limit: int): clans = await coc_client.search_clans(name=name, limit=limit) # return a list of tuples of name/tag pair ie. [(name, tag), (another name, another tag)] return [(n.name, n.tag) for n in clans]
command_prefix = '+' key_names = 'test' else: command_prefix = '//' key_names = 'windows' class COCClient(coc.EventsClient): async def on_event_error(self, event_name, exception, *args, **kwargs): await clash_event_error(self.bot, event_name, exception, *args, **kwargs) coc_client = coc.login(creds.email, creds.password, client=COCClient, key_names=key_names, throttle_limit=30, key_count=3) description = "A simple discord bot to track donations of clan families in clash of clans." async def get_pref(bot, message): if not message.guild: # message is a DM return "+" prefix = bot.prefixes.get(message.guild.id, "+") return commands.when_mentioned_or(prefix)(bot, message)
from cogs.utils.error_handler import error_handler from database.botdb import BotDatabase description = """ Bot made to help with the Buds Alliance Owner : Ay355#0905 The prefix is , Tags can be typed with or without the hashtag Please DM or ping Ay355 if you need any help """ coc_client = coc.login(creds.coc_dev_email, creds.coc_dev_password, client=coc.EventsClient, correct_tags=True) intents = discord.Intents.all() intents.members = True initial_extensions = ( "cogs.game_info", "cogs.database_bg", "cogs.auto_role", "cogs.moderation", "cogs.attack_strats", "cogs.misc", # "cogs.welcome" )
For most commands, you will need to include a clan name or tag. You can use the clan tag (with or without the hashtag) or you can use the clan name (spelling is kind of important). There are easter eggs. Feel free to try and find them!""" # class COCClient(coc.EventsClient): # async def on_event_error(self, event_name, exception, *args, **kwargs): # await clash_event_error(self.bot, event_name, exception, *args, **kwargs) coc_client = coc.login(coc_email, coc_pass, client=coc.EventsClient, key_count=2, key_names=coc_names, throttle_limit=25, correct_tags=True) links_client = discordlinks.login(settings['links']['user'], settings['links']['pass']) intents = discord.Intents.none() intents.guilds = True intents.guild_messages = True intents.guild_reactions = True intents.members = True intents.emojis = True
import os import coc import discord from coc.errors import NotFound t = gettext.translation('bot', 'locale', languages=['ko'], fallback=True) _ = t.gettext print(_('Logging in to COC API...')) email = os.getenv('COC_BOT_EMAIL') password = os.getenv('COC_BOT_PASSWORD') coc_client = coc.login(email, password, client=coc.EventsClient) clan_tag = '#U8YJLRQU' members_last_updated = {} recently_notified_war_clans = set() dc_bot_token = os.getenv('DISCORD_BOT_TOKEN') dc_client = discord.Client() topology_id = 653614701476839450 general_id = 653614701476839453 fellow_id = 662257591581147152 developer_id = 668082046131765248
import coc import util import io import os coc_dev_email = "*****@*****.**" # Clash of Clans Developer Account email coc_dev_password = "******" # Clash of Clans Developer Account password fname="fullroster.csv" async def main(): roster = await util.get_full_roster(client) roster_data = await util.build_roster_table(client,roster) with io.open(fname, "w", encoding="utf-8") as f: f.write(roster_data) print(fname,'stored in', os.path.dirname(os.path.abspath(fname))) client = coc.login(coc_dev_email ,coc_dev_password) client.loop.run_until_complete(main()) #client.close()